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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
formxshape
Forum Newbie
Posts: 4
Joined: Tue Dec 01, 2009 7:35 am

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

Post 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.
maneetpuri
Forum Commoner
Posts: 60
Joined: Tue Oct 07, 2008 6:32 am

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

Post 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,
formxshape
Forum Newbie
Posts: 4
Joined: Tue Dec 01, 2009 7:35 am

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

Post 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...
Marinusjvv
Forum Commoner
Posts: 29
Joined: Wed Dec 02, 2009 5:59 am

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

Post 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);
}
Post Reply