简体   繁体   中英

Replacing innertext of XML node using PHP DOMDocument

I want to replace innertext of a XML node my XML file named test.xml is

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>no</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

I want to change the value of loop and description tag both, and it should be saved in test.xml like:

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description Changing Here</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>We will play later</description>
    </item>
</ads>

I tried code in PHP:

<?
    $file = "test.xml";
    $fp = fopen($file, "rb") or die("cannot open file");
    $str = fread($fp, filesize($file));
    $dom=new DOMDocument();
    $dom->formatOutput = true;
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($str) or die("Error");
    //$dom->load("items.xml");

    $root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild)

    $loop=$root->getElementsByTagName('loop')->item(0);//->textContent;
    //echo $loop;
    if(trim($loop->textContent)=='no')
    {
        echo 'ok';
        $root->getElementsByTagName('loop')->item(0)->nodeValue ='yes';
    }
    echo "<xmp>NEW:\n". $dom->saveXML() ."</xmp>";
?>

I tried only for loop tag.I don't know how to replace nodevalue in description tag . When I run this page it shows output like:

ok
NEW:
<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

It gives the value yes in browser but don't save it in test.xml any reason?

So, since you have created DOMDocument you can use DOMXpath . Or keep using getElementsByTagName()

You could do this (but only in that context):

$descriptions = $root->getElementsByTagName('description');
foreach($descriptions as $nodeDesciption)
{
    $nodeDesciption->nodeValue ='Your custom value';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM