Milos Cuculovic
Milos Cuculovic

Reputation: 20223

PHP DOMDocument converts & to &amp - how to keep row value

I am using the PHP DOMDocument and at one moment I am using the createTextNode

$copyrightNode = $doc->createTextNode('©');
$copyrightContainer = $dom_output->createElement('copyright-statement');

$copyrightContainer->appendChild($copyrightNode);

In the XML that is generated some time later, I am getting:

<copyright-statement>&amp;#x000A9;</copyright-statement> 

And my goal is to have

<copyright-statement>&#x000A9;</copyright-statement> 

Any idea on how to do that?

Thank you in advance.

Upvotes: 0

Views: 793

Answers (2)

Alf Eaton
Alf Eaton

Reputation: 5463

When PHP outputs an XML document, any characters that cannot be represented in the specified output encoding will be replaced with numeric entities (either decimal or hexadecimal, both are equivalent):

<?php

$dom = new DOMDocument;

$node = $dom->createElement('copyright-statement', '©');
$dom->appendChild($node);

$dom->encoding = 'UTF-8';
print $dom->saveXML(); // <copyright-statement>©</copyright-statement>

$dom->encoding = 'ASCII';
print $dom->saveXML(); // <copyright-statement>&#169;</copyright-statement>

Upvotes: 1

dave
dave

Reputation: 64695

The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity.

Example:

<?php 
$copyrightNode = $doc->createEntityReference("copy"); 
$copyrightContainer = $dom_output->createElement('copyright-statement');
$copyrightContainer->appendChild($copyrightNode);

To create &#x000A9; you could (I believe) do:

$copyrightNode = $doc->createCDATASection("&#x000A9;"); 
$copyrightContainer = $dom_output->createElement('copyright-statement');
$copyrightContainer->appendChild($copyrightNode);

Upvotes: 0

Related Questions