FirstName Las...">

Updating XML node using PHP

I have an XML file test.xml

<?xml version="1.0"?> <info> <user> <name> <firstname>FirstName</firstname> <lastname>Last Name</lastname> <nameCoordinate> <xName>125</xName> <yName>20</yName> </nameCoordinate> </name> </user> </info> 

I am trying to update node xName and yName using PHP when submitting a form. So, I uploaded the file using simplexml_load_file (). PHP form action code below

 <?php $xPostName = $_POST['xName']; $yPostName = $_POST['yName']; //load xml file to edit $xml = simplexml_load_file('test.xml'); $xml->info->user->name->nameCoordinate->xName = $xPostName; $xml->info->user->name->nameCoordinate->yName = $yPostName; echo "done"; ?> 

I want to update node values, but the code above seems to be wrong. Can someone help me fix this?

UPDATE: My question is somewhat similar to this Updating an XML file using PHP , but here I am loading the XML from an external file, and also updating the element, not the attribute. Where my confusion lies.

+12
xml php simplexml
Jan 20 '11 at 2:00
source share
2 answers

You are not accessing node. In your example, $xml contains the root node <info/> . Here's a great tip: always name the variable that stores your XML document after its root root , this will prevent such confusion.

In addition, as Ward Muylaert pointed out, you need to save the file.

Here's a corrected example:

 // load the document // the root node is <info/> so we load it into $info $info = simplexml_load_file('test.xml'); // update $info->user->name->nameCoordinate->xName = $xPostName; $info->user->name->nameCoordinate->yName = $yPostName; // save the updated document $info->asXML('test.xml'); 
+26
Jan 20 2018-11-11T00:
source share

You must write the changes to the file, use the asXML method of the SimpleXMLElement element.

+3
Jan 20 2018-11-21T00:
source share



All Articles