简体   繁体   English

如何使用php更改xml节点属性值?

[英]How to change xml node attribute value with php?

How to change XML node attribute value with PHP?如何使用 PHP 更改 XML 节点属性值? I tried a bit but I couldn't figure it out, can you help me?我试了一点,但我无法弄清楚,你能帮我吗?

I want to change user1 password.我想更改 user1 密码。

<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.如果您只有一个目标用户,则您真的不需要foreach 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.看看它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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