Вы можете расширить класс SimpleXMLElement с помощью функции simples, чтобы сделать это
class ExSimpleXMLElement extends SimpleXMLElement {
/**
* Add CDATA text in a node
* @param string $cdata_text The CDATA value to add
*/
private function addCData($cdata_text) {
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
/**
* Create a child with CDATA value
* @param string $name The name of the child element to add.
* @param string $cdata_text The CDATA value of the child element.
*/
public function addChildCData($name, $cdata_text) {
$child = $this->addChild($name);
$child->addCData($cdata_text);
return $child;
}
/**
* Modify a value with CDATA value
* @param string $name The name of the node element to modify.
* @param string $cdata_text The CDATA value of the node element.
*/
public function valueChildCData($name, $cdata_text) {
$name->addCData($cdata_text);
return $name;
}
}
использование:
$xml_string = <<<XML
<root>
<item id="foo"/>
</root>
XML;
$xml5 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml5->valueChildCData($xml5->item, 'mysupertext');
echo $xml5->asXML();
$xml6 = simplexml_load_string($xml_string, 'ExSimpleXMLElement');
$xml6->item->addChildCData('mylittlechild', 'thepunishment');
echo $xml6->asXML();
результат:
<?xml version="1.0"?>
<root>
<item id="foo"><![CDATA[mysupertext]]></item>
</root>
<?xml version="1.0"?>
<root>
<item id="foo">
<mylittlechild><![CDATA[thepunishment]]></mylittlechild>
</item>
</root>