I know this question is asked many times before but still can’t find the desired result I have been looking for parsing xml document using php DOMDocument function.
Initially my xml document named ‘local.xml’ contains the following script
<?xml version="1.0" encoding="utf-8"?>
<config>
<global>
<host><![CDATA[name123]]></host>
<username><![CDATA[root45]]></username>
</global>
</config>
I want to change “<host><![CDATA[name123]]></host>” to “<host><![CDATA[name456]]></host>“
I have php code that can change the value inside tag. Here is the php code
<?php
$doc = new DOMDocument();
$doc->load('local.xml');
$config = $doc->getElementsByTagName( "global" );
foreach( $config as $global )
{
$hosts=$global->getElementsByTagName( "host" );
$usernames=$global->getElementsByTagName( "username" );
$a = "<![CDATA[name456]]>";
$hosts1=$hosts->item(0)->nodeValue=$a;
}
$doc->save('local.xml');
?>
When i execute the above code, the output in the xml file is coming as
<?xml version="1.0" encoding="utf-8"?>
<config>
<global>
<host><![CDATA[name456]]></host>
<username><![CDATA[root45]]></username>
</global>
</config>
How can I convert "<" to "<" and ">" to ">" in xml document?
I have tried $a = htmlspecialchars("<![CDATA[name456]]>"); as well as $a = html_entity_decode("<![CDATA[name456]]>"); still it is giving the same output as seen above.
Finally After some more hours and hours of trails and errors, I managed to solve it. Had Daniel Sloof not shown the tip, my code would have been useless. Thanks Daniel Sloof
here is the final code
By adding null value to
$oldcdatait will empty the value inside<host><![CDATA[name123]]></host>tag this will become<host></host>in xml fileNow we add a new value to
$newcdatait will then be appended to<host></host>by using appendChild($newcdata) and it will become<host><![CDATA[name456]]></host>