Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 argument of SimpleXMLElement::addChild can contain & ? Do i have to use some htmlentities on the manufacturer name ?

like image 968
Benjamin Crouzier Avatar asked Apr 26 '26 11:04

Benjamin Crouzier


1 Answers

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]]>

like image 66
Benjamin Crouzier Avatar answered Apr 29 '26 01:04

Benjamin Crouzier