简体   繁体   中英

How to change xml node attribute value with php?

How to change XML node attribute value with PHP? I tried a bit but I couldn't figure it out, can you help me?

I want to change user1 password.

<Users>
                    <User Name="user1">
                        <Option Name="Pass">123456</Option>
                        <Option Name="fname">first name</Option>
                        <Option Name="lname">last name</Option>
                    </User>
                    <User Name="user2">
                        <Option Name="Pass">123456</Option>
                        <Option Name="fname">first name</Option>
                        <Option Name="lname">last name</Option>
                    </User>
     <Users>

Php code:

$xmlfile = "users.xml";
$xml = simplexml_load_file($xmlfile);
$xml->asXML($xmlfile);

foreach( $xml->Users->xpath("User [@Name='user1']") as $t ) {
  $t->xpath("Option[@Name='Pass']") = '654321';
}

if(!$rv = $xml->asXML($xmlfile)){
      $mesaj = 'error! \n ';
      echo $mesaj;
}    else {
    echo "Password Changed.";
}

You don't really nee foreach if you have only one target user. Try changing

foreach( $xml->Users->xpath("User [@Name='user1']") as $t ) {
  $t->xpath("Option[@Name='Pass']") = '654321';
}

to

$target = $xml->xpath('//User[@Name="user1"]/Option[@Name="Pass"]')[0];
$target[0]="654321";
echo($xml->asXml());

and see if it works.

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