0

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 &lt; and &gt;. How to fix that? How to set inner html of an element that contains other html?

1 Answer 1

1

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 that node from doc2 into doc1. Only after you imported that node - you can use the appendChild 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>
Sign up to request clarification or add additional context in comments.

8 Comments

it says: ARGUMENT 1 PASSED TO DOMNODE::APPENDCHILD() MUST BE AN INSTANCE OF DOMNODE, BOOLEAN GIVEN
when I do this public static function setInnerHTML(\DOMDocument $dom, \DOMNode &$element, $html_string) { $dom2 = new \DOMDocument(); $dom2->loadHTML($html_string); $element->appendChild($dom->importNode($dom2->firstChild)); }
I'm almost sure you should use &$dom and also node the second parameter of the importNode method.
ARGUMENT 1 PASSED TO DOMNODE::APPENDCHILD() MUST BE AN INSTANCE OF DOMNODE, BOOLEAN
I think the $dom2->loadHTML() fails but doesn't give an error cause $dom2->firstChild is null or false
|

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.