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

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -