1

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

  • Instead of looking for `

    ` nodes, search the container `

    ` and iterate over its text childs: http://stackoverflow.com/a/15703501/345031
    – mario Jan 17 '17 at 12:48

1 Answers1

5

Use DOMXPath:

$xpath = new DOMXpath($domDocument);

foreach ($xpath->query('//div/text()') as $textNode) {
    echo $textNode->nodeValue;
}
Maya Shah
  • 950
  • 7
  • 17