SimpleXMLElement::addChild doesn't seem to work with certain strings
In the effiliation pluggin for prestashop, i've found this code:
$values->addChild('marque', '<![CDATA['.$product['manufacturer_name'].']]>');
when in $product['manufacturer_name']
, i have Cyril & Nathalie Daniel
, the output is <![CDATA[Cyril
,
as opposed to the normal case: <![CDATA[Foo Bar]]>
Can the 2nd argum开发者_高级运维ent of SimpleXMLElement::addChild can contain &
? Do i have to use some htmlentities on the manufacturer name ?
My problem is described here:
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".
The solution proposed php.net (htmlentities or htmlcspecialchars) is not a good one, so i came up with what salathe suggested:
<?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));
}
}
and instead of
$values->addChild('marque', '<![CDATA['.$product['manufacturer_name'].']]>');
use :
$values->addChild('marque')->addCData($product['manufacturer_name']);
Output is now <![CDATA[Cyril & Nathalie Daniel]]>
Another possibility is to remember that SimpleXMLElement is doing a double-decode -- instead of mapping &
to &
(single-decode), it seems to work to just map &
to &amp;
to start with. Your child ends up with &
in the XML like it should.
You may need to encode your manufacturer name with htmlentities by the looks of it. This should be ok within the CDATA tags I'd have thought though.
Try this:
$values->addChild('marque', '<![CDATA['.htmlentities($product['manufacturer_name']).']]>');
精彩评论