2

Having spent a few hours researching I have been unable to come up with an answer for this. I am trying to send an XML string to a third party so I need to encode some characters, in this case single and perhaps double quotes. I use the PHP XML Dom to achieve this but the saveXML() function always unencodes quotes it seems. A very simple example is below and when you view the output, ' has been replaced with ' but the others still have their codes. Can anyone explain why this is and how I can get around it (without doing a str_replace). Thanks.

$XMLDoc = new DOMDocument('1.0', 'utf-8');
$comments = $XMLDoc->createElement('Comments');
    $text = $XMLDoc->createElement('Text', "An apostrophe here < ' > Pound sign: £");
$comments->appendChild($text);
$XMLDoc->appendChild($comments);
echo $XMLDoc->saveXML();

1 Answers1

2

You need to use a createEntityReference function to get it to pass through unmolested.

Example:

$XMLDoc = new DOMDocument('1.0', 'utf-8');
$comments = $XMLDoc->createElement('Comments');

$text1 = $XMLDoc->createTextNode('An apostrophe here < ');
$text2 = $XMLDoc->createEntityReference('apos');
$text3 = $XMLDoc->createTextNode(' > Pound sign: ');
$text4 = $XMLDoc->createEntityReference('pound');

$comments->appendChild($text1);
$comments->appendChild($text2);
$comments->appendChild($text3);
$comments->appendChild($text4);
$XMLDoc->appendChild($comments);
echo $XMLDoc->saveXML();

Note that some items are encoded by default by createTextNode. < and > are encoded, pound signs are not. Hope this helps!

mainegreen
  • 237
  • 1
  • 2
  • 8
  • 2
    Thanks for the reply but this all seems very cumbersome just for the sake of having an encoded apostrophe. Is there no setting in the php DOM to prevent it from unencoding entities? To me this sounds like a php bug so I might report it to them – Robin Charisse Feb 15 '12 at 10:05