Jump to content

DOM: How to get text from tag, but without its child nodes text


expablo

Recommended Posts

I have a HTML like this:

 

<div >Text 1
  <div>Text 2</div>
  Text 3
</div>

 

How to get only the text from first level div (Text 1, Text 3)?

Without text 2.

 

 

$html = <<<END
<div >Text 1
  <div>Text 2</div>
  Text 3
</div>
END;

$dom_doc = new DOMDocument();
@$dom_doc->loadHTML($html);

$nodelist = $dom_doc->getElementsByTagName('div');

foreach($nodelist as $node) {
   echo $node->nodeValue . "\n";
}

 

With this code I get:

 

Text 1
   Text 2
   Text 3

Text 2

 

But I want only:

 

Text 1
Text 3

 

Hope that makes sense.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.