Search code examples
phpxmldomdomdocument

Amend node value in existing XML document and print result with DOM PHP


I am looking for the best method to replace a node value using DOM in PHP.

An example XML would be, which is stored as data.xml:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

I have been following https://www.w3schools.com/php/php_xml_dom.asp, which works great to print out the XML file without any edits using the following code:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("data.xml");


print $xmlDoc->saveXML();
?>

Now I'm not sure how to go about editing the values of, for example, change Jani to Smith and print the new changed xmlDoc.


Solution

  • Try:

    $xpath = new DOMXPath($xmlDoc);
    $from = $xpath->query('/note//from')[0];
    $from->nodeValue="John";
    echo $xmlDoc->saveXML();
    

    Output:

    <?xml version="1.0" encoding="UTF-8"?>
    <note>
    <to>Tove</to>
    <from>John</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>