Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

Updating XML node with PHP

I've 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'm trying to update the node xName & yName using PHP on a form submission. So, I've loaded the file using simplexml_load_file(). The PHP form action code is 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 the node values but the above code seems to be incorrect. Can anyone help me rectify it??

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Here's the 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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...