Page 1 of 1

PHP: replace text in an xml node, keeping CDATA. How?

Posted: Tue Dec 01, 2009 9:13 pm
by formxshape
Please can someone show me how to replace the text in a XML document node.

For example we have this simple xml document:

Code: Select all

 
<?xml version="1.0"?>
<root>
    <branch>
        <leaf><![CDATA[Hello]]></leaf>
    </branch>
</root>
 

I want to change the word 'Hello' to 'Goodbye'.

How do I do that in php? I'm completely stuck.
Please someone show me a simple way. I've googled for hours and can't find anyone talking in a straight manor about how to do this.

Thanks in advance.

Re: PHP: replace text in an xml node, keeping CDATA. How?

Posted: Wed Dec 02, 2009 3:31 am
by maneetpuri
Hi,

You will have to develop an XML parser and the logic will be opening the XML file in read write mode, find the node and replace its value with the desired one. You can find help on various XML functions of PHP at the following URL: -

http://in2.php.net/manual/en/refs.xml.php

Cheers,

Re: PHP: replace text in an xml node, keeping CDATA. How?

Posted: Wed Dec 02, 2009 8:20 am
by formxshape
thanks Maneet,

but It looks really confusing - can anyone give me just a little code snippet?
I can't get my head around all the dom php xml stuff...

Re: PHP: replace text in an xml node, keeping CDATA. How?

Posted: Wed Dec 02, 2009 8:25 am
by Marinusjvv
Well, if you were opening the Xml document, for example, you could use:

Code: Select all

$lines = file("something.xml");
 
foreach($lines as $line_num => $line)
{
    $line = str_replace("Hello","Goodbye",$line);
}