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.";
}
CodePudding user response:
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.