Ben*_*ier 2 php xml simplexml cdata
在prestashop的effiliation插件中,我发现了这段代码:
$values->addChild('marque', '<![CDATA['.$product['manufacturer_name'].']]>');
Run Code Online (Sandbox Code Playgroud)
当$product['manufacturer_name']我Cyril & Nathalie Daniel输入时,输出是<![CDATA[Cyril,而不是正常情况:<![CDATA[Foo Bar]]>
SimpleXMLElement :: addChild的第二个参数可以包含&吗?我是否必须在制造商名称上使用一些htmlentities?
我的问题在这里描述:
请注意,虽然addChild()转义为"<"和">",但它不会转义"&"符号.
解决方案提出php.net(htmlentities或htmlcspecialchars)并不是一个好的解决方案,所以我想出了salathe建议的内容:
<?php
class SimpleXMLExtended extends SimpleXMLElement // http://coffeerings.posterous.com/php-simplexml-and-cdata
{
public function addCData($cdata_text)
{
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
Run Code Online (Sandbox Code Playgroud)
而不是
$values->addChild('marque', '<![CDATA['.$product['manufacturer_name'].']]>');
Run Code Online (Sandbox Code Playgroud)
使用 :
$values->addChild('marque')->addCData($product['manufacturer_name']);
Run Code Online (Sandbox Code Playgroud)
输出现在 <![CDATA[Cyril & Nathalie Daniel]]>