1

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.

1
  • 1
    There is some notes on replacing a node value in this doc, but I wonder if this is easier in SimpleXML! Commented Dec 19, 2020 at 9:41

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

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.