script: adding attribute to XML file

To avoid the repetitive task of manually adding the same attribute to all elements at the same level in an XML file, use this PHP 5 script, which requires three parameters.

In the first addatt script, the attribute values will be added manually .
The second script, addval, reads values from the array it creates from another XML file.

Add attributes without values

For example, from this document:

<doc>
<car model="xxx" />
<car model="yyy" />
</doc>

We want to automatically add the attribute "speed" to the tags "car."

<doc>
<car model="xxx" speed="80" />
<car model="yyy" speed="90" />
</doc>

Use of script

It requires three parameters.

The command format is as follows:

solp addatt fname tname aname

The new XML document is saved as test.xml.
We then delete the original file to rename test.xml under its name.

Scriptol code

DOMDocument docsrc = DOMDocument("1.0")
docsrc.load(filename) DOMNodeList dnl = docsrc.getElementsByTagName(tname)
DOMElement de = null int i = 0 while i < dnl.length
de = dnl.item(i)
de.setAttribute(aname, "")
let i + 1 docsrc.save(filename)

PHP code

$docsrc=new DOMDocument("1.0");
$docsrc->load($filename);

$dnl=$docsrc->getElementsByTagName($tname);
$i = 0;
while($i<$dnl->length)
{
$de=$dnl->item($i);
$de->setAttribute($aname,""); $i+=1; } $docsrc->save($filename);

Add attributes with their values

Use of script

The last parameter is added - the name of the XML file in which the values ​ ​ are read.

Code

The previous function is modified to read values from an array and assign them to elements.

This assumes that the elements have an identifier that is also in the array. To do this, create an associative array with identifiers as keys and attribute values as values.

Reading values from an XML file

DOMNodeList dnl = docval.getElementsByTagName(tname) 
DOMElement de = null array a = {} for int i in 0 -- dnl.length
de = dnl.item(i) text id = de.getAttribute(tagid) // get the ID
text value = de.getAttribute(aname) // get the value of the property for this ID a[id] = value
/for

Assigning values

while i < size
de = dnl.item(i)
text id = de.getAttribute(tagid)
de.setAttribute(aname, a[id])
let i + 1

This time, attributes are assigned based on the tag name and element ID, which should be the key in the array.

Download source code (/PHP)