开发者

SimpleXMLElement::addChild doesn't seem to work with certain strings

开发者 https://www.devze.com 2023-03-29 14:51 出处:网络
In the effiliation pluggin for prestashop, i\'ve found this code: $values->addChild(\'marque\', \'<![CDATA[\'.$product[\'manufacturer_name\'].\']]>\');

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 &amp; (single-decode), it seems to work to just map & to &amp;amp; to start with. Your child ends up with &amp; 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']).']]>');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号