Get the text content of a node, but ignore child nodes

后端 未结 3 370
情话喂你
情话喂你 2021-01-06 04:35

  a
   b 

both $foo->textContent and $foo->nodeValue return a

相关标签:
3条回答
  • 2021-01-06 04:37

    This might be helpful. Using what I found here and here

    $txt = "";
    foreach($foo->childNodes as $node) {
        if ($node->nodeType == XML_TEXT_NODE) {
            $txt .= $node->nodeValue;
        }
    }
    
    0 讨论(0)
  • 2021-01-06 04:46

    Try this code

    $doc = new DOMDocument();
    $doc->loadXML('<root><foo>a<bar>b</bar></foo><foo>bar</foo></root>');
    $foos = $doc->getElementsByTagName('foo');
    foreach($foos as $v){
       echo $v->firstChild->wholeText.'<br />';
    }
    

    The firstChild property of DOMNode returns a DOMText object as there is a "text node" before <bar> in first <foo>

    0 讨论(0)
  • 2021-01-06 04:50

    Use firstChild :

    $foo->firstChild->textContent;
    
    0 讨论(0)
提交回复
热议问题