Search code examples
phpdomxpath

How to get first level plain text from a node PHP?


Here is the brief code I'm struggling with:

<a>value<span>no need</span><a>

I'm currently working on DOMXPath, what I need is to get the immediate value of tag a, which is "value", whereas I actually get an additional "no need" when using nodeValue property:

$xpath->query('a')->item(0)->nodeValue;//give me "value no need"

How to get the value from the first level only, exclude the nested node. Thank you !


Solution

  • Your expression needs to match the text node itself, not its tag, so f.e.

    $xpath->query('a/text()')->item(0)->nodeValue
    

    or alternatively, you could use childNodes to navigate to the text node from the "a" tag:

    $xpath->query('a')->item(0)->childNodes->item(0)->nodeValue