Node and Attribute Values Modification Using PHP

Sep 04, 2013, by admin

Node and Attribute Values Modification Using PHP

Sometimes you want to alter the value of a node or an attribute in an xml document. You can use PHP’s SimpleXML to read the XML file, assign new values to elements or attribute and save the changes back to the file.

<?php
    $xml = simplexml_load_file(“data.xml”);
    /* Aletr value of a node */
    $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());
    echo “XML file successfully updated”;
    ?>

In this above example, 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 string, is combined with the file_put_contents() function to overwrite the original XML document with the new data.

Hope this might be helpful for you thanks to PHPZAG.com for the coding