我使用 SimpleXMLElement 创建 xml 但它无法处理 &。这是我的代码
$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>
如何解决这个问题。我想要一个针对所有特殊字符的解决方案。
最佳答案
您必须将其替换为例如 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 & 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();
关于php - 如何在 SimpleXML PHP 中处理 & 和其他特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28669407/