简体   繁体   中英

Access and update attribute value in XML using XPath and PHP

this is an extension to my previous post today which can be found here: Click Here

Now I want to access another attribute based upon the id attribute and change that as well. Here is my modified xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<document>
    <item id="a12sd">       
        <name>James</name>
        <age years="25"/>
        <pdf>0023.pdf</pdf>
    </item>
    <item id="rdf23">       
        <name>Alex</name>
        <age years="35"/>
        <pdf>0178.pdf</pdf>
    </item>
    <item id="2we34">       
        <name>Tom</name>
        <age years="25"/>
        <pdf>0886.pdf</pdf>
    </item>
    <item id="123de">       
        <name>Robby</name>
        <age years="28"/>
        <pdf>1239.pdf</pdf>
    </item>
</document> 

I have been able to update the tags using this code:

$id = "a12sd";
$xml = simplexml_load_file('items.xml');  

$itemsList = $xml->xpath('/document/item[@id = "a12sd"]');             

$itemsList[0]->name = "Arnold";

$xml->asXml("items.xml");

Now I need to access the attribute age for the id="a12sd" and update the age to say: 26

Any idea how I can reach that attribute for given id and change that value.

Note: before changing the value the user knows only the "id" value, so based upon id value I want to change years attribute for that particular id.

Thanks

$itemsList[0]->age->attributes()->years = 26;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM