Reading list Switch to dark mode

    How to edit the XML attributes in PHP

    Updated 9 June 2017

    Today we will learn , how to edit the xml element attributes in PHP.

    First of all, we need to create a sample xml file. So we have created the demo.xml file as follows

     * Webkul Software.
     * @category Webkul
     * @package xml
     * @author Webkul
     * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (
     * @license
     <?xml version="1.0" encoding="utf-8"?>
       <add key="Id" value="0"/>
       <add key="Name" value="Test"/>

    After creating the xml file, we have created the php file as follows:

     * Webkul Software.
     * @category Webkul
     * @package api
     * @author Webkul
     * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (
     * @license
     $xml = simplexml_load_file('demo.xml');
     if ($xml->xpath('//appSettings/add[@key="Id"]')[0]) {
         $xml->xpath('//appSettings/add[@key="Id"]')[0]->attributes()['value'] = 1;
     if ($xml->xpath('//appSettings/add[@key="Name"]')[0]) {
         $xml->xpath('//appSettings/add[@key="Name"]')[0]->attributes()['value'] = 'Demo';

    Function Description:

    simplexml_load_file : The function is used to convert the xml file into SimpleXMLElement object. In this function first parameter is file path where we pass the path of our xml file. Syntax for the function is :

    Start your headless eCommerce
    Find out More

    SimpleXMLElement simplexml_load_file ( string $filename  string $class_name , int $options , string $ns , bool is_prefix)

    xpath : The function searches the XML element for children matching the XPath path. Like in the example it will search the add element with in the appsetting that has an attribute key and their value is Id or Name.

    asXML : The function is just reverse of simplexml_load_file and converts the xml object to the xml format.

    When we execute the php file for the first time it will produce the following output.

    We can see the changes in the demo.xml file or we can execute the php file again, we will see the changed values in the xml file as follows :

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home