0

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>
2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Mapper99
0
$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.

0

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?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.