Search code examples
phpxmlsimplexml

How do I edit an XML file in SimpleXML, based on the contents of the XML, if there are multiple values of the same tag?


Say I have an XML file like this.

<users>
  <user>
    <username>desbest</username>
    <email>[email protected]</email>
    <password>testpass1</password>
  </user>
  <user>
    <username>demo</username>
    <email>[email protected]</email>
    <password>demo</password>
  </user>
</users>

How do I use XPath to select the desbest user, then use php to edit the password under the desbest user, and save it as a file?

I have searched Google and Stack Overflow and I haven't found the answer.

Here is my current code.

// 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);

Solution

  • You can achieve this just with SimpleXML - you don't need to involve DOMDocument at all.

    The xpath method returns the <user> element you're looking for. You can then modify it simply by updating the password property (or add new ones, or attributes, etc). This updates the underlying SimpleXMLElement object, which you can then write back to the file as a string using 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());
    

    See https://eval.in/923654 for an example