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>

Recommended Answers

All 2 Replies

$desc->lastname = "Penner";

I believe your problem lies with this line of code. If you echo $desc to screen I think you will find that it relates to the lastname tag, not the user tag, so it is inserting a child of the lastname tag which is not what you want. If you change that line to this:

$desc = "Penner";

I think that will be closer to what you are after.

Thanks for your reply. When I change that line, the XML data is not updated at all. I believe that the simpleXML syntax for updating a node needs to have a certain format. Perhaps I am just setting a regular PHP variable using this syntax?

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.