PHP DOM - counting child nodes?

后端 未结 3 764
情深已故
情深已故 2020-12-20 15:52

HTML snippet #1

headline

HTML snippe

相关标签:
3条回答
  • 2020-12-20 16:09

    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);
    
    0 讨论(0)
  • 2020-12-20 16:14

    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>';
    }
    
    0 讨论(0)
  • 2020-12-20 16:34

    Firefox,Chrome and most other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.Check Here

    0 讨论(0)
提交回复
热议问题