PHP XML 实体编码问题 [英] PHP XML Entity Encoding issue

查看:25
本文介绍了PHP XML 实体编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几个小时的研究,我一直无法为此找到答案.我正在尝试将 XML 字符串发送给第三方,因此我需要对一些字符进行编码,在这种情况下是单引号,也可能是双引号.我使用 PHP XML Dom 来实现这一点,但 saveXML() 函数似乎总是对引号进行解编码.下面是一个非常简单的示例,当您查看输出时,'已被替换为 ' 但其他人仍然有他们的代码.任何人都可以解释为什么会这样以及我如何解决它(不执行 str_replace).谢谢.

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

推荐答案

您需要使用 createEntityReference 函数才能使其不受干扰地通过.

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

示例:

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

请注意,某些项目默认由 createTextNode 编码.<和 > 被编码,英镑符号不是.希望这会有所帮助!

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

这篇关于PHP XML 实体编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆