tags:

views:

196

answers:

1

Hello,

Using PHP, what would be a simple way to use XQuery to find the first instance of a given HTML element and then replace all the HTML inside that element?

So far, I've got this:

$myHTML = '<strong>Some <em>HTML</em></strong>';
$domDocument = new DOMDocument('1.0');
@$domDocument->loadHTML($content);
$xpd = new DOMXPath($domDocument);
$result = $xpd->query('//div[@id="main"]');
$result->item(0)->nodeValue = $myHTML;
$output = $domDocument->saveHTML();

This almost works. One problem is that the value of $myHTML is XML-escaped in the output. To resolve this issue, maybe I could create a temporary DOMDocument, load it with my HTML, then iterate through it, adding its nodes to $domDocument.

Seems complex for doing something simple like this. Is there a simplier way of doing this?

Thanks!

+1  A: 

Take a look at my answer concerning a similar (same?) problem.

Ionuț G. Stan
+1 for me, I didn't know C14N method, that's pretty awesome !
SleepyCod
Thanks! appendXML() didn't work well for me due to issues with the replacement HTML. Think that the replacement code must not have been 100% valid.So, I put a simple placeholder value as a nodeValue ('###insert-content-here###'), then did a str_replace() on the output of $domDocument->saveHTML() to insert the HTML.
Ben Gribaudo