1

I have seem similar solutions else where but I haven't been able to convert to work with my own code.

I have a function that splits an html string between the paragraph tags and returns in an array. Code is as follows...

$dom = new DOMDocument();
$dom->loadHTML($string);
$domx = new DOMXPath($dom);
$entries = $domx->evaluate("//p");
$result = array();
foreach ($entries as $entry) {
    $result[] = '<' . $entry->tagName . '>' . $entry->nodeValue .  '</' . $entry->tagName . '>';
}

return $result;

Can someone assist me to remove the nodeValue element from this so it returns the paragraph content with html tags complete?

1

2 Answers 2

4

You need to call saveHTML on the ownerDocument property:

$result[] = $entry->ownerDocument->saveHTML($entry);
Sign up to request clarification or add additional context in comments.

5 Comments

@AdamJones - I ran Orangepill's code, and it worked fine with saveXML.
@PédeLeão I was thinking it might be barfing on saveXML if the contents where not well formed. I know valid HTML != valid XML
save html doesnt improve it either im afraid. I have added the html to the question now...
Change your xpath query to "//p|//ul" to include the ul's in the result
I have another small issue it seems. Its to do with encoding. Some chrs in the page appear as â instead of ” Also spaces in some places appear as Â. Any ideas?
2
$dom = new DOMDocument();
$dom->loadHTML($string);
$entries = $dom->getElementsByTagName('p');
$new_dom = new DOMDocument();
foreach ($entries as $entry) {
    $new_dom->appendChild($new_dom->importNode($entry, TRUE));
}
$result = $new_dom->saveHTML()

5 Comments

this returns no content im afraid
@AdamJones - I just ran it again with no problem.
Ive just added a link to the html Im using (within a string variable) that has the code run on it if this helps ?
the ul/li's are not in p tags... that's why they are missing from the results.
@AdamJones - I just ran it with the HTML that you provided. It works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.