4

I have an XML file with some CDATA nodes. I want to change the text inside the CDATA node (keeping it as CDATA node). So, I guess I first need to read the CDATA node and then write it back. But, I am not sure how to do that in PHP. I was able to create a new CDATA node but how can I edit a CDATA node? Is there a direct way to do that?

Thanks.

4
  • What library are you using (i.e. how are you manipulating the XML file)? Commented Jun 28, 2010 at 19:40
  • PHP/XML - DOMDocument/SimpleXML Commented Jun 28, 2010 at 19:42
  • there is an issue with this in simplexml, take a look at this bug report: bugs.php.net/bug.php?id=42421 Commented Jun 28, 2010 at 19:42
  • Yeah. SimpleXML probably isn't the right one to manipulate XML but I think DOMDocument should be good enough to do what I am trying to do. I just cannot seem to find the right way. Commented Jun 28, 2010 at 19:48

2 Answers 2

2

I'm not versed in PHP (lots of Java DOM experience) but I think you need to replace the text node with a new CDATA text node. See

http://www.php.net/manual/en/domdocument.createcdatasection.php

and

http://www.php.net/manual/en/domnode.replacechild.php

Sign up to request clarification or add additional context in comments.

Comments

1

I fixed it on my own:

$nodes = $xml->getElementsByTagName('tagname'); $oldTitleNode = null; $newTitleNode = null; //Iterate for each <title> tag foreach ($nodes as $node) { if ($node->parentNode->getAttribute('name')== $tag_name_value){ $oldTitleNode = $node; //Create new CDATA Node $newTitleNode=$node->parentNode->appendChild($xml->createElement('tagname')); $cdata=$xml->createCDATASection($update_title); $newTitleNode->appendChild($cdata); //Replace the Existing CDATA Node $node->parentNode->replaceChild($newTitleNode, $oldTitleNode); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.