使用 PHP 更新 XML 节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4748014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating XML node with PHP
提问by ptamzz
I've an XML file test.xml
我有一个 XML 文件 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 更新节点 xName 和 yName。所以,我已经使用 simplexml_load_file() 加载了文件。PHP 表单操作代码如下
<?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 PHPbut 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.
更新:我的问题有点类似于使用 PHP 更新 XML 文件,但在这里,我从外部文件加载 XML,并且我正在更新元素,而不是属性。这就是我的困惑所在。
回答by Josh Davis
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.
您没有访问正确的节点。在您的示例中,$xml
保存根节点<info/>
。这里有一个很好的提示:始终在根节点之后命名保存 XML 文档的变量,这样可以防止这种混淆。
Also, as Ward Muylaert pointed out, you need to save the file.
此外,正如 Ward Muylaert 指出的,您需要保存文件。
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');
回答by Ward Muylaert
回答by Ruhith Udakara
try like this.
像这样尝试。
$xmlDoc = new \DOMDocument;
$xmlDoc->load('Books.xml');
$response = $xmlDoc->getElementsByTagName('Text');
foreach ($response as $node){
$node->nodeValue = 'test';
}
$xmlDoc->saveXML();
this might not the best answer but it worked for me.
这可能不是最好的答案,但它对我有用。