user7430453
user7430453

Reputation: 11

PHP DomDocument get text after tag

I have this in my php file.

<?php
$str = '<div>
    <p>Text</p>
    I need this text...
    <p>next p</p>
    ... and this
</div>
';

$dom=new DomDocument();
$dom->loadHTML($str);
$p = $dom->getElementsByTagName('p');
foreach ($p as $item) {
    echo $item->nodeValue;
}

This gives me the correct text for the p tags, but I also need the the text between the p tags ("I need this text...", "...and this").

Anyone know how to get the text after the p tag?

Best

Upvotes: 1

Views: 1863

Answers (1)

Maya Shah
Maya Shah

Reputation: 970

Use DOMXPath:

$xpath = new DOMXpath($domDocument);

foreach ($xpath->query('//div/text()') as $textNode) {
    echo $textNode->nodeValue;
}

Upvotes: 5

Related Questions