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 (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
    
     <?xml version="1.0" encoding="utf-8"?>
     <appSettings>
       <add key="Id" value="0"/>
       <add key="Name" value="Test"/>
     </appSettings>

    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 (https://webkul.com)
     * @license https://store.webkul.com/license.html
     */
    
     <?php
    
     $xml = simplexml_load_file('demo.xml');
    
     print_r("<pre>");
     print_r($xml);
     print_r("</pre>");
    
     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';
     }
    
     $xml->asXML('demo.xml');
     ?>

    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
    now.
    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