php - XPath return null if attribute not found? -
i'm using xpath query find attribute values. however, want go through each div , if attributes not found, return nothing. there way this?
html:
<div id="a" class="a">text</div> <div>text</div> <div id="b" class="b">text</div>   xpath:
$values = $xpath->query('//div/@id | //div/@class');   result:
array('a', 'a', 'b', 'b');   desired result:
array('a', 'a', '', '', 'b', 'b');   as of now, i'm kind of in xpath already, , stay in direction right now.
why not selecting <div> elements , use domelement::getattribute() obtain attibute values? note method return empty string if current element didn't has attribute requested. (what should want).
try this:
$html = <<<eof <div id="a" class="a"></div> <div></div> <div id="b" class="b"></div> eof;  $doc = new domdocument(); $doc->loadhtml($html); $selector = new domxpath($doc);  $result = array(); foreach($selector->query('//div') $div) {     $result []= $div->getattribute('id');     $result []= $div->getattribute('class'); }  var_dump($result);   output:
array(6) {   [0] =>   string(1) "a"   [1] =>   string(1) "a"   [2] =>   string(0) ""   [3] =>   string(0) ""   [4] =>   string(1) "b"   [5] =>   string(1) "b" }      
Comments
Post a Comment