As the title says, I am struggling with add cdata text in my code. And yes, I tried the most popular example here on stackoverflow but there the class is extended and some different approach is used. What I did so far is this. Not sure also if it is good practice to just concatenate a <![CDATA[ my text here ]]>
as a simple string.
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><SHOP></SHOP>");
foreach ($res as $item) {
$shopitem = $xml->addChild("SHOPITEM");
$shopitem->addChild("ITEM_ID", $item['item_id']);
$shopitem->addChild("ITEMGROUP_ID", $item['itemgroup_id']);
$shopitem->addChild("PRODUCTNAME", $item['productname']);
$shopitem->addChild("MANUFACTURER", TEXT HERE SHOULD BE CDATA);
}
Header('Content-type: text/xml');
print($xml->asXML());
My Answer:
To add CDATA to the "MANUFACTURER" field in your XML generated with SimpleXMLElement and addChild method, you can use the following approach:
php
$xml = new SimpleXMLElement(" ");
foreach ($res as $item) {
$shopitem = $xml->addChild("SHOPITEM");
$shopitem->addChild("ITEM_ID", $item['item_id']);
$shopitem->addChild("ITEMGROUP_ID", $item['itemgroup_id']);
$shopitem->addChild("PRODUCTNAME", $item['productname']);
// Add CDATA to the "MANUFACTURER" field
$manufacturer = $shopitem->addChild("MANUFACTURER");
$node = dom_import_simplexml($manufacturer);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($item['manufacturer']));
}
Header('Content-type: text/xml');
print($xml->asXML());
In this code snippet, we first create a SimpleXMLElement object and add the necessary child elements. To add CDATA to the "MANUFACTURER" field, we create a new element for "MANUFACTURER", get the DOM node of this element, and then append a CDATA section with the manufacturer text.
This way, the manufacturer text will be enclosed in CDATA in the generated XML output.
Rate this post
3 of 5 based on 5269 votesComments