PHP DOM - counting child nodes? -
html snippet #1
<div> </div> <div> <h1>headline</h1> </div> html snippet #2
<div></div> <div><h1>headline</h1></div> php code
$doc = new domdocument(); $doc->loadhtml($x); $xpath = new domxpath($doc); $divs = $xpath->query("//div"); foreach ($divs $div) echo $div->childnodes->length,"<br />"; output $x = snippet #1
1
3
output $x = snippet #2
0
1
see working demo: http://codepad.viper-7.com/11bgge
my questions
1. how can be?
2. how count child nodes correctly dom?
edit:
silkfire said, empty space considered text node. set
$doc->preservewhitespace = false; but results still same: http://codepad.viper-7.com/bng5io
any ideas?
just count non-text nodes in loop:
$count = 0; foreach($div->childnodes $node) if(!($node instanceof \domtext)) $count++; print $count; using xpath:
$nodesfromdiv1 = $xpath->query("//div[1]/*")->length; $nodesfromdiv2 = $xpath->query("//div[2]/*")->length; to remove empty text nodes, when preservewhitespace=false not working (as suggested in chat):
$textnodes = $xpath->query('//text()'); foreach($textnodes $node) if(trim($node->wholetext) === '') $node->parentnode->removechild($node);
Comments
Post a Comment