Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

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 ?

Upvotes: 3

Views: 5594

Answers (3)

Mark Leighton Fisher
Mark Leighton Fisher

Reputation: 5693

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.

Upvotes: 1

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41865

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

Upvotes: 9

Curlybraces
Curlybraces

Reputation: 24

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']).']]>');

Upvotes: -1

Related Questions