如果同一个标签有多个值,如何根据XML的内容在SimpleXML中编辑XML文件?

时间:2017-12-21 11:28:37

标签: php xml simplexml

假设我有这样的XML文件。

<users>
  <user>
    <username>desbest</username>
    <email>desbest@example.com</email>
    <password>testpass1</password>
  </user>
  <user>
    <username>demo</username>
    <email>nobody@example.com</email>
    <password>demo</password>
  </user>
</users>

如何使用XPath选择desbest用户,然后使用php编辑desbest用户下的密码,并将其另存为文件?

我搜索了Google和Stack Overflow,但我还没有找到答案。

这是我目前的代码。

// print_r($xml);
$newpass = "mynewpass";
// $newpass = password_hash($newpass, PASSWORD_DEFAULT);
$nodes = $xml->xpath(sprintf(" //users/user[(username = \"$myusername\")] ")); 
// print_r($nodes);
// $nodes[0]->password = "$newpass";
$domnode = dom_import_simplexml($nodes[0]);
$nodepath = $domnode->getNodePath();
// $xml = $xml->$nodepath->password = $newpass;

// $danodepath = $nodes[0]->getNodePath();

// print_r($nodes);
// $xml->users->user["(username = \"$myusername\")"] = "$newpass";
print_r($xml);
echo "<hr>";
print_r($nodepath);

2 个答案:

答案 0 :(得分:2)

您只需SimpleXML即可实现此目标 - 您根本无需涉及DOMDocument

xpath方法返回您要查找的<user>元素。然后,您只需更新密码属性(或添加新的属性或属性等)即可对其进行修改。这将更新基础SimpleXMLElement对象,然后您可以使用asXML将其作为字符串写回文件。

$filename = 'file.xml';
$sxml = simplexml_load_file($filename);

$username = "desbest";
$user = $sxml->xpath("./user[./username = '{$username}']")[0];
$user->password = 'testpassCHANGED';

file_put_contents($filename, $sxml->asXML());

请参阅https://eval.in/923654以获取示例

答案 1 :(得分:0)

DOMDocument示例:

$source = '<users>
  <user>
    <username>desbest</username>
    <email>desbest@example.com</email>
    <password>testpass1</password>
  </user>
  <user>
    <username>demo</username>
    <email>nobody@example.com</email>
    <password>demo</password>
  </user>
</users>';

$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($source);

$xpath = new DOMXPath($dom);

$myusername = htmlspecialchars("desbest", ENT_XML1 | ENT_QUOTES, 'UTF-8');
$expression = sprintf('/users/user[(username="%s")]', $myusername);

$users = $xpath->query($expression);
if($users->length) {
    $user = $users->item(0);
    $password = $xpath->query('password', $user)->item(0);
    $password->nodeValue = 'new password';
}

file_put_contents('filename.xml', $dom->saveXML());