7
<foo>
  a
  <bar> b </bar>
</foo>

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

How can I get just a (the text from the node, without text from any child nodes)

Alex
  • 66,732
  • 177
  • 439
  • 641

3 Answers3

9

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;
    }
}
Community
  • 1
  • 1
jonhopkins
  • 3,844
  • 3
  • 27
  • 39
  • 1
    Don't know why it's so hard to find an actual answer to that simple question. After searching for hours, this answer IS the best answer found so far. Should be upvoted. – Patrick L. Mar 05 '18 at 14:03
4

Use firstChild :

$foo->firstChild->textContent;
zessx
  • 68,042
  • 28
  • 135
  • 158
4

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>

Ejaz
  • 8,719
  • 3
  • 34
  • 49