PHP Code-Snippet: Replacing CDATA content of a SimpleXMLElement object

This little challenge took me too much time to not letting people know the solution I came up with. So when I am forced to work with PHP and want to process XML files, I prefer using PHP’s SimpleXML interface, because I found out that I need the least number of LOC for querying particular nodes within a document. It also provides methods for manipulating the DOM tree, but it appears that the possibilities are highly limited and in particular there is no method for creating CDATA sections. Here is the result of my Stackoverflow.com and try&error session.

Assumption:
We have a SimpleXMLElement object which is representing a node containing a CDATA sestion as node content.

Goal:
Replace content of the CDATA section and provide content of the manipulated document.

Possible solution:
Get a DOM node from the SimpleXMLElement objet, delete its CDATA child and create a new CDATA section with new content.

Snippet:

// get DOM node
$node = dom_import_simplexml($mySimpleXmlElement); 
	
	   
// remove existing CDATA ($node->childNodes->item(1) does not seem to work)
foreach($node->childNodes as $child) {
  if ($child->nodeType == XML_CDATA_SECTION_NODE) {
    $node->removeChild($child);
  }
}

// add new CDATA
$no = $node->ownerDocument; 
$node->appendChild($no->createCDATASection($myNewContent)); 

// print result
echo $xml->asXML();
Advertisements

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: