Marc
Marc

Reputation: 9567

DOM Document - How to get the text inside a tag without the inner tags

Assume I have a dom_document containing the following html and it is put in a variable called $dom_document

<div>
  <a href='something'>some text here</a>
  I want this
</div>

What i would like is retrieve the text that is inside the div tag ('I want this'), but not the a tag. What i do is the following:

$dom_document->nodeValue;

Unfortunately with this statement I have the a tag in with it. Hope someone can help. Thank you in advance. Cheers. Marc

Upvotes: 1

Views: 1336

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173662

You can use XPath for it:

$xpath = new DOMXpath($dom_document);
$textNodes = $xpath->query('//div/text()');

foreach ($textNodes as $txt) {
    echo $txt->nodeValue;
}

Upvotes: 2

Related Questions