Masha
Masha

Reputation: 857

php export xml CDATA escaped

I am trying to export xml with CDATA tags. I use the following code:

$xml_product = $xml_products->addChild('product');
$xml_product->addChild('mychild', htmlentities("<![CDATA[" . $mytext . "]]>"));

The problem is that I get CDATA tags < and > escaped with &lt; and &gt; like following:

 <mychild>&lt;![CDATA[My some long long long text]]&gt;</mychild>

but I need:

<mychild><![CDATA[My some long long long text]]></mychild> 

If I use htmlentities() I get lots of errors like tag raquo is not defined etc... though there are no any such tags in my text. Probably htmlentities() tries to parse my text inside CDATA and convert it, but I dont want it either.

Any ideas how to fix that? Thank you.

UPD_1 My function which saves xml to file:

public static function saveFormattedXmlFile($simpleXMLElement, $output_file) {
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML(urldecode($simpleXMLElement->asXML()));
    $dom->save($output_file);

}

Upvotes: 1

Views: 1975

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

A short example of how to add a CData section, note the way it skips into using DOMDocument to add the CData section in. The code builds up a <product> element, $xml_product has a new element <mychild> created in it. This newNode is then imported into a DOMElement using dom_import_simplexml. It then uses the DOMDocument createCDATASection method to properly create the appropriate bit and adds it back into the node.

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Products />');

$xml_product = $xml->addChild('product');
$newNode = $xml_product->addChild('mychild');
$mytext = "<html></html>";
$node = dom_import_simplexml($newNode);
$cdata = $node->ownerDocument->createCDATASection($mytext);
$node->appendChild($cdata);
echo $xml->asXML();

This example outputs...

<?xml version="1.0" encoding="UTF-8"?>
<Products><product><mychild><![CDATA[<html></html>]]></mychild></product></Products>

Upvotes: 2

Related Questions