HTML snippet #1
headline
HTML snippe
Just count non-text nodes in your loop:
$count = 0;
foreach($div->childNodes as $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
is not working (as I suggested in the chat):
$textNodes = $xpath->query('//text()');
foreach($textNodes as $node)
if(trim($node->wholeText) === '')
$node->parentNode->removeChild($node);
Whitespace is considered a node because it is a text() node (DOMText
).
You can make this work by changing your foreach
loop:
foreach ($divs as $div) {
echo $div->childNodes->length - $xpath->query('./text()', $div)->length, '<br>';
}
Firefox,Chrome and most other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.Check Here