Use SimpleXML to read the XML file, assign new values to elements or attributes, and save the changes back to the file:
- <?php
- // read XML tree
- $xml = simplexml_load_file("data.xml")↩
- or die("ERROR: Cannot create SimpleXML object");
- // alter value of node <weight>
- $xml->weight = 3000;
- // alter value of attribute <weight units=>
- $xml->weight['units'] = "gm";
- // write modified tree back to file as XML string
- file_put_contents("data.xml", $xml->asXML()) ↩
- or die("ERROR: Could not write to file");
- echo "XML file successfully updated";
- ?>
Comments
In this listing, the original XML file is first read in, and elements and attributes are altered by assigning new values to the corresponding object properties and arrays. The asXML() method, typically used to output the XML tree as a string, is combined with the file_put_contents() function to overwrite the original XML document with the new data.