Please can someone show me how to replace the text in a XML document node that is using CDATA.

For example I have this simple xml document on my server:

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

If I want to change the word 'Hello' to 'Goodbye' - How do I do that in php?

I can't find any tutorials about how to use dom to change it. and simplexml is useless in this case. Please some just show me the code...

    <?php
    // syntax highliting is screwed up when including the xml tag, so removed that
    // do put it back in
    /* <?xml version="1.0" ?> */
    $xml = '<root>
    <branch>
    <leaf><![CDATA[Hello]]></leaf>
    </branch>
    </root>';
    
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    
    $nodes = $dom->getElementsByTagName('leaf');
    foreach($nodes as $n) {
    	$text = $n->firstChild->nodeValue;
    	if ($text == 'Hello') {
    		$n->firstChild->nodeValue = 'Goodbye';
    	}
    }
    ?>
    

      Thank you johanafm,

      that works perfectly.

        Write a Reply...