Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write CDATA using SimpleXmlElement?

I have this code to create and update xml file:

<?php $xmlFile    = 'config.xml'; $xml        = new SimpleXmlElement('<site/>'); $xml->title = 'Site Title'; $xml->title->addAttribute('lang', 'en'); $xml->saveXML($xmlFile); ?> 

This generates the following xml file:

<?xml version="1.0"?> <site>   <title lang="en">Site Title</title> </site> 

The question is: is there a way to add CDATA with this method/technique to create xml code below?

<?xml version="1.0"?> <site>   <title lang="en"><![CDATA[Site Title]]></title> </site> 
like image 401
quantme Avatar asked Jun 07 '11 03:06

quantme


People also ask

How do I add CDATA to XML?

CDATA sections may be added anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string " <! [CDATA[ " and end with the string " ]]> ".

What is CDATA PHP?

C Data Handles ¶C array elements can be accessed as regular PHP array elements, e.g. $cdata[$offset] C arrays can be iterated using foreach statements. C arrays can be used as arguments of count(). C pointers can be dereferenced as arrays, e.g. $cdata[0]

Can we use CDATA in XML attribute?

No, The markup denoting a CDATA Section is not permitted as the value of an attribute.


1 Answers

Got it! I adapted the code from this great solution (archived version):

    <?php          // http://coffeerings.posterous.com/php-simplexml-and-cdata     class SimpleXMLExtended extends SimpleXMLElement {        public function addCData( $cdata_text ) {         $node = dom_import_simplexml( $this );          $no   = $node->ownerDocument;                  $node->appendChild( $no->createCDATASection( $cdata_text ) );        }          }      $xmlFile    = 'config.xml';          // instead of $xml = new SimpleXMLElement( '<site/>' );     $xml        = new SimpleXMLExtended( '<site/>' );          $xml->title = NULL; // VERY IMPORTANT! We need a node where to append          $xml->title->addCData( 'Site Title' );     $xml->title->addAttribute( 'lang', 'en' );          $xml->saveXML( $xmlFile );          ?> 

XML file generated:

    <?xml version="1.0"?>     <site>       <title lang="en"><![CDATA[Site Title]]></title>     </site> 

Thank you Petah

like image 70
quantme Avatar answered Oct 01 '22 08:10

quantme