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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.