简体   繁体   中英

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);

}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM