Reputation: 5316
I am editing the xml file using this code
$xml = simplexml_load_file($xmlfile) or die ("Unable to load XML file!");
$event->title = $newtitle;
$event->description = $newdescription;
file_put_contents($xmlfile, $xml->asXML());
I want to add a CDATA in description.I used this code
$event->description = '<![CDATA['.$newdescription.']]>';
But in xml the <
and >
are converted as <
and >
.How i can retain CDATA
as it is .Is any other method for editing.Thanks in advance.
Actually i want to edit this xml file
<events date="06-11-2010">
<event id="8">
<title>Proin porttitor sollicitudin augue</title>
<description><![CDATA[Lorem nunc.]]></description>
</event>
</events>
<events date="16-11-2010">
<event id="4">
<title>uis aliquam dapibus</title>
<description><![CDATA[consequat vel, pulvinar.</createCDATASection></description>
</event>
<event id="1"><title>You can use HTML and CSS</title>
<description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events>
With id
Upvotes: 2
Views: 2147
Reputation: 5062
I think that you need to use DOM when your needs are more complex and no longer simple. There is a method createCDATASection.
Here's a basic example:
$dom=new DOMDocument();
$xml='data.xml';
$dom->load($xml);
$cdata=$dom->createCDATASection('<p>Foo</p>');
foreach ($dom->getElementsByTagName('item') as $item) {
$item->getElementsByTagName('content')->item(0)->appendChild($cdata);
}
$dom->save($xml);
The XML that goes with this:
<?xml version="1.0" encoding="utf-8"?>
<data>
<item>
<title>Test</title>
<content><![CDATA[<p>Foo</p>]]></content>
</item>
</data>
With regards to your example and comment, the following should help you:
$dom=new DOMDocument();
$dom->validateOnParse = true;
$xml='data.xml';
$dom->load($xml);
// Unless the ID attribute is recognised
foreach ($dom->getElementsByTagName('event') as $event) {
$event->setIdAttribute('id', true);
}
$event = $dom->getElementById("1");
foreach ($event->getElementsByTagName('description') as $description) {
$cdata=$dom->createCDATASection('<p>'. $description->nodeValue .'</p>');
$description->replaceChild($cdata, $description->childNodes->item(0));
}
$dom->save($xml);
Upvotes: 3
Reputation: 70460
Essentially, SimpleXML
will escape all values for XML use, so a lot of the reasons to use CDATA
nodes aren't there. If you do need them however, it cannot be done in SimpleXML
, use another alternative like DOMDocument
and it's function createCDATASection()
Upvotes: 2
Reputation: 18721
Try
$xml = simplexml_load_file($xmlfile,'SimpleXMLElement', LIBXML_NOCDATA);
?
Upvotes: -2