Page 1 of 1

PHP simplexml: Edit an XML file, big problem with CDATA

Posted: Tue Dec 01, 2009 8:11 am
by formxshape
I'm trying to create a very simple web page that will load an xml file, displace a nodes content in a html paragraph text box form - allowing a user to edit the text - and after clicking 'submit' have php rewrite the nodes content.

I've manage to do just that, however I need the text to be wrapped in CDATA tags as it'll later be used in a Flash website. Also the original xml file has CDATA tags but when php writes back to the node it loses the CDATA bit.

I'm really confused about it all, I'm just php beginner, I've spent 8 hours googling it trying to learn about what's going on, but I'm still clueless - even more so now...

So here's what I've got:

An XML file:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<site>
<aboutpage>
    <copya><![CDATA[This is the about page text.]]></copya>
</aboutpage>
</site>
 
A html/php page with:

Code: Select all

 
<?php
$file = 'sitecontent.xml';
$xml = simplexml_load_file($file);
if (!isset($_POST['submit'])) {
}else{
$xml->aboutpage[0]->copya = $_POST["element_1"];
$xml->asXML("sitecontent.xml"); 
}
?>
 
<form id="form_1" class="abc"  method="post" action="<?php echo $PHP_SELF;?>">
 
<textarea id="element_1" name="element_1" class="element textarea medium"><?php echo $xml->aboutpage[0]->copya;?></textarea>
 
<input id="saveForm" class="button_text" type="submit" name="submit" value="Save" />
</form> 
 
I've tried:

Code: Select all

$xml->aboutpage[0]->copya = "<![CDATA[" . $_POST["element_1"] . "]]>";
but it comes out looking like this in the XML file:
<![CDATA[This is the about page text now edited.]]>
and I'm having problems with " turning into \"

Someone please help, please explain it all to me....

Re: PHP simplexml: Edit an XML file, big problem with CDATA

Posted: Tue Dec 01, 2009 9:00 am
by AbraCadaver
You'll probably not like simplexml for this. Check out the DOM extension. FWIW though, you can try this and see:

Code: Select all

$xml = simplexml_load_file($file, 'SimpleXMLElement', LIBXML_NOCDATA);
As for the quote escaping, you most likely have magic_quotes_gpc turned on in php.ini. Turn it off, or try something like this:

Code: Select all

if(get_magic_quotes_gpc()) {
    $element = stripslashes($_POST['element_1']);
}
$xml->aboutpage[0]->copya = $element;
-Shawn

Re: PHP simplexml: Edit an XML file, big problem with CDATA

Posted: Tue Dec 01, 2009 7:15 pm
by formxshape
Thanks for the help. I'll have to learn the php DOM stuff then - do you know any good tutorials(that talk in a language a beginner will understand)?