Hi there,

I am trying to update a node in an XML file using PHP.

Here is the XML:

<users>
   <user>
     <id>1</id>
     <firstname>Bob</firstname>
     <lastname>Marley</lastname>
   </user>
   <user>
     <id>2</id>
     <firstname>Bruce</firstname>
     <lastname>Springsteen</lastname>
   </user>
</users>

How can I go about searching the XML file for all tags where "id=2" and setting the firstname and lastname nodes to new values?

Any replies would be greatly appreciated!

Mapper

Recommended Answers

All 2 Replies

http://php.net/SimpleXML, You might want to take a look at the xpath stuff.

I have taken a brief look into SimpleXML and have created the following. I just can't get the XML to update:

$file = 'officedata.xml';
$xml = simplexml_load_file($file);
$lastname = $xml->xpath('//user[id="2"]/lastname');
$xml_string='';

        while(list( , $node) = each($lastname))
        {

            $xml_string .= $node->asXML(); 
            $xml_string='newlastname';
        }

echo $xml_string;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.