使用PHP更新XML节点 [英] Updating XML node with PHP

查看:54
本文介绍了使用PHP更新XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件test.xml

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>

我正在尝试更新节点xName& yName在表单提交中使用PHP.因此,我已经使用simplexml_load_file()加载了文件. PHP表单操作代码如下

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??

更新: 我的问题有点类似于使用PHP更新XML文件,但是在这里,我正在从外部文件加载XML,也正在更新元素,而不是属性.那就是我的困惑所在.

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.

推荐答案

您没有访问正确的节点.在您的示例中,$xml保存根节点<info/>.这里有个很好的提示:始终在XML文档的根节点之后命名用于保存XML文档的变量,这样可以避免此类混淆.

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.

而且,正如Ward Muylaert指出的那样,您需要保存文件.

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

这是更正的示例:

// 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');

这篇关于使用PHP更新XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆