Search code examples
phpxpathdomdocument

How to get the main text of an element by DOMDocument


I want to get the main text of an element without the child elements with DOMDocument. For example,

<span>
This is the main
    <i>more</i>
    <b>extra</b>
<span>

I get the text by

$text=$g->query('//span')[0]->nodeValue;

but how can I get only the text value, which is under span. Here, only This is the main text by ignoring any child elements.


Solution

  • Use the text() node test:

    echo $g->query('//span/text()')[0]->nodeValue;
    

    Output is:

    This is the main
    

    This will only find text nodes that are direct children of a <span>.