Click to See Complete Forum and Search --> : Updating values in XML file


Root Ninja
12-09-2008, 09:01 AM
Hi all,

First thread so let me know if theres too little info.

I have an XML file:

<?xml version="1.0" encoding="utf-8"?>

<users>

<user id ="0">
<username>SHiDi</username>
<password>c822c1b63853ed273b89687ac505f9fa</password>
<active>1</active>
</user>

<user id= "1">
<id>1</id>
<username>John</username>
<password>0659c7992e268962384eb17fafe88364</password>
<active>0</active>
</user>

</users>

Could someone tell how I would use PHP to update the username where id=1?

Any feedback is welcome, thank you.

rpgfan3233
12-09-2008, 10:19 AM
You can use XPath to update it:
<?php

// Since this example outputs the result, text/plain works better than
// the default of text/html. ;)
header("Content-Type: text/plain");

$doc = new DOMDocument();

if ($doc->load('users.xml', LIBXML_NOBLANKS))
{
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('/users/user[@id=1]/username', $doc);
$nodeList->item(0)->nodeValue = 'Joe';
// If you want to save the document, use save() instead of
// saveXML(), and don't echo anything. This also means you could
// remove the header() call above.
echo $doc->saveXML(), "\n";
}

?>