Googlebot
Googlebot

Reputation: 15673

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.

Upvotes: 0

Views: 37

Answers (1)

Sean Bright
Sean Bright

Reputation: 120634

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

Upvotes: 2

Related Questions