简体   繁体   中英

PHP XML Entity Encoding issue

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();

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM