1

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.";
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, good job ;)
@flash Glad it worked for you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.