Php change xml attribute value

Basics

I suggest you select all nodes with xpath:

$xml = simplexml_load_string[$x]; // assume XML in $x
$strings = $xml->xpath["//string"];

The above statement will select all nodes as SimpleXml elements into an array.
The double slash in //string will take regardless of their position in the tree.

Now it is simple to iterate over $strings and set the new value:

foreach [$strings as $string] 
    $string["value"] = "new value";

Note that the changes applied to $strings happen in $xml, so:

echo $xml->asXML[];

will show the changes.

see it working: //eval.in/499427

Expanded

Of course, you might want to select only certain nodes, e.g. all having name="name". In this case, you can tell xpath like:

$strings = $xml->xpath["//string[@name='name']"];

Note the condition set in [] and @name referring to the attribute name.

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 [//webkul.com]
 * @license //store.webkul.com/license.html
 */

 
 
   
   
 

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 [//webkul.com]
 * @license //store.webkul.com/license.html
 */

 

Chủ Đề