Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

<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)

like image 544
Alex Avatar asked Mar 29 '13 12:03

Alex


People also ask

What is the difference between innerText and textContent?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.

What is. textContent in JavaScript?

What is textContent in JavaScript. It is a property that allows us to get or set the text content of a node, or an element. Setting the textContent property will remove and replace the child nodes with the new text node.

What does childNodes return?

childNodes returns nodes: Element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes.

Which property of a text Node would you use to set the value of that Node?

The nodeValue property of the Node interface returns or sets the value of the current node.


3 Answers

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;
    }
}
like image 68
jonhopkins Avatar answered Oct 22 '22 08:10

jonhopkins


Use firstChild :

$foo->firstChild->textContent;
like image 32
zessx Avatar answered Oct 22 '22 09:10

zessx


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>

like image 4
Ejaz Avatar answered Oct 22 '22 07:10

Ejaz