0

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>&lt;![CDATA[name456]]&gt;</host>
        <username><![CDATA[root45]]></username> 
    </global>
</config>

How can I convert "&lt;" to "<" and "&gt;" 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.

2 Answers 2

3

Use DOMDocument::createCDATASection.

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

1 Comment

Thanks, after going through hours and hours of coding and many trails and errors with DOMDocuemtn::createCDATASection, im still stuck in this. I would be gratefull if you would provide me with code to implement this correctly
0

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

<?php
$doc = new DOMDocument();
$doc->load('local.xml');
$config = $doc->getElementsByTagName( "global" );
foreach( $config as $global )
{
    $hosts=$global->getElementsByTagName( "host" );
    $oldcdata=$hosts->item(0)->nodeValue="";
    $newcdata=$doc->createCDATASection("name456");
    $hosts1=$hosts->item(0)->appendChild($newcdata);
}
$doc->save('local.xml');
?>

By adding null value to $oldcdata it will empty the value inside <host><![CDATA[name123]]></host> tag this will become <host></host> in xml file

Now we add a new value to $newcdata it will then be appended to <host></host> by using appendChild($newcdata) and it will become <host><![CDATA[name456]]></host>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.