Jump to content

Updating XML nodes using SimpleXML adds extra node


FredPenner

Recommended Posts

I have a very simple script that basically searches an xml file for a node based on the id of another node. I then update the node I found with a new value. For some reason my code is not performing the update. It is actually creating another node within the existing node. Any idea why?

 

XML:

<?xml version="1.0" encoding="UTF-8" ?> 
<users>
<user>
  <id>1</id> 
  <firstname>Bob</firstname> 
  <lastname>Marley</lastname> 
  </user>
<user>
  <id>2</id> 
  <firstname>Bruce</firstname> 
  <lastname>Springsteen</lastname> 
  </user>
</users>

 

PHP Code:

 

<?php

$file = "officedata.xml";

$xml=simplexml_load_file($file);

foreach ($xml->xpath('//user[id="2"]/lastname') as $desc) {
echo "$desc\n";
$desc->lastname = "Penner"; 
}

file_put_contents($file, $xml->asXML()); 

?>

 

The updated XML looks like this:

 

<?xml version="1.0" encoding="UTF-8" ?> 
<users>
<user>
  <id>1</id> 
  <firstname>Bob</firstname> 
  <lastname>Marley</lastname> 
  </user>
<user>
  <id>2</id> 
  <firstname>Bruce</firstname> 
<lastname>
  Springsteen 
  <lastname>Penner</lastname> 
  </lastname>
  </user>
</users>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.