Jay Bienvenu
Jay Bienvenu

Reputation: 3291

PHP: Using DOM classes to build <script> elements

I have an HTML generator that uses the DOM classes to build documents and produce HTML. My target is HTML-compatible XHTML as outlined in Appendix C of the XHTML 1.0 spec.

This is a problem producing <script> elements:

$document = new \DOMDocument();
$element = $document->createElement('script');
$script = $document->createTextNode('console.log(1 && 1);');
$element->appendChild($script);
$document->appendChild($element);
echo $document->saveXML($document->childNodes[0]);

Actual output:

<script>console.log(1 &amp;&amp; 1);</script>

Desired output:

<script>console.log(1 && 1);</script>

How do I get the desired output with the entities not escaped?

The correct answer must account for the fact that this situation occurs in a generator that generates all sorts of HTML elements, not just <script>, and generates proper XHTML. (That's why I use saveXML instead of saveHTML in the first place.) If an answer causes the generator to fail or misproduce other HTML elements, it isn't the correct answer.

Upvotes: 1

Views: 143

Answers (2)

sagecoder
sagecoder

Reputation: 101

Using change saveXML to saveHTML

echo $document->saveHTML($document->childNodes[0]);

Upvotes: 0

chris85
chris85

Reputation: 23880

Don't saveXML, use saveHTML.

$document = new \DOMDocument();
$element = $document->createElement('script');
$script = $document->createTextNode('console.log(1 && 1);');
$element->appendChild($script);
$document->appendChild($element);
echo $document->saveHTML($document->childNodes[0]);

Demo: https://3v4l.org/63H0L

In XML an & is marking an entity.

Upvotes: 2

Related Questions