PHP SimpleXML and CData
It's not that often I need to mess around with CData using PHP SimpleXML but whenever I do I always seem to forget a couple of basics and spend 20 min looking everything up again. So here's that stuff on one page... XML
<mydoc> <element id="1"><![CDATA[my stuff goes here]]></element> </mydoc>Extracting CData from an SimpleXML object (LIBXML_NOCDATA is the important bit):
$xml = simplexml_load_file('my-file.xml', NULL, LIBXML_NOCDATA);
$description = $xml->xpath("//item[@id='1']");
var_dump($description);
Inserting CData into a tree:
class SimpleXMLExtended extends SimpleXMLElement{
public function addCData($cdata_text){
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
$doc = new SimpleXMLExtended($xml);
$element = $doc->addChild('response');
$node_note = $element->addChild('note');
$node_note->addCData('my cdata guff');
var_dump($doc->asXML());