如何处理&和SimpleXML PHP中的其他特殊字符

时间:2015-02-23 08:16:55

标签: php

我使用SimpleXMLElement来创建xml但它无法处理&amp ;.这是我的代码

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', 'You & Me');
$name->addAttribute('no', '1');
echo $contacts->asXML();

这是输出

<?xml version="1.0" encoding="UTF-8"?>
<Contacts><name no="1">You </name></Contacts>

如何解决这个问题。我想要一个适合所有特殊角色的解决方案。

2 个答案:

答案 0 :(得分:2)

您必须将其替换为例如html代码http://www.ascii.cl/htmlcodes.htm或检查此http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', 'You &amp; Me');
$name->addAttribute('no', '1');
echo $contacts->asXML();

你也可以使用函数htmlspecialchars来做到这一点

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$name = $contacts->addChild('name', htmlspecialchars('You & Me', ENT_QUOTES, "utf-8"));
$name->addAttribute('no', '1');
echo $contacts->asXML();

答案 1 :(得分:2)

这应该适用于你而不使用html代码,因为这样它会自动转义它:

(因为addChild()仅转义<>,但不转义&

$contacts = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Contacts></Contacts>');
$contacts->name[0] = 'You & Me';
$contacts->name[0]->addAttribute('no', '1');
echo $contacts->asXML();

输出(源代码):

<?xml version="1.0" encoding="UTF-8"?>
<Contacts><name no="1">You &amp; Me</name></Contacts>