I have a PHP script that uses DOMDocument and DOMXPath to find and replace merge codes in an HTML template. A simple example might be:
<html>
<head>
<title>Title</title>
</head>
<body>
<p>Hello {greeting}!</p>
<table><tr>
<td>Details:</td>
<td>{details}</td>
</tr></table>
</body>
</html>
The following code substituted fields based on an associative array where the key matches the merge field:
private function substituteFields (DOMNode $node, $fields)
{
$x = new DOMXPath ($node->ownerDocument);
foreach ($fields as $field => $value)
{
$query = $x->query (".//text()[contains(., '{" . $field . "}')]", $node);
foreach ($query as $subnode)
{
$subnode->nodeValue = str_replace ("{" . $field . "}", $value, $subnode->nodeValue);
}
}
}
This is working well.
However, some merge codes will need HTML substituted into them:
$fields ['greeting'] = "Joe Soap";
$fields ['details'] = "<div class='details'>Details here</div>";
The substitution is happening, but the HTML is being escaped, which is probably a sensible idea in most cases.
Can I work around this?