I am trying to set the nodeValue of an element like this:
$element->nodeValue = get_include_contents(DIR_APP . Config::getParam("layout_dir").$itemTemplateFilePath);
get_include_contents
function returns an html which look like this:
<li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: 'onclick', Action: 'deleteThePerson'">X</a></li>
The problem is that the < and > gets replaced by the <
and >
. How to fix that? How to set inner html of an element that contains other html?
If you want to add html
block into your DOM
tree you should use the appendChild
and not the nodeValue
method.
The problem is that you need first to create a DON Node
.
Here is a trick on how to do this:
// This will be the original doc we work on.
$doc1 = new DOMDocument();
$doc1->loadHTML("<html><body><p></p></body></html>");
$element = $doc1->getElementsByTagName('p')[0];
// Here is the trick - we create a new document
$doc2 = new DOMDocument();
$s = '<li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: \'onclick\', Action: \'deleteThePerson\'">X</a></li>';
// and load the html we need into that document
$doc2->loadHTML($s);
// Now we can append the node from `doc2` into `doc1`
$element->appendChild($doc1->importNode($doc2->getElementsByTagName('li')[0], true));
echo $doc1->saveHTML();
The important thing that you need to remember is that you must use the
importNode
method in order to move thatnode
fromdoc2
intodoc1
. Only after you imported that node - you can use theappendChild
function.
The output in the above example will be:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p><li>Person <b>{{ $name }}</b> is <span>{{ $age }}</span> years old. <a href="" data-id="{{ $id }}" data-event="Event: 'onclick', Action: 'deleteThePerson'">X</a></li></p></body></html>