XML文件内容未使用PHP更新



每次运行代码时,文件都会更新,我可以看到文件上次编辑的日期和时间会更新,但XML文件中的内容不会更新。

我刚刚尝试更新以下XML代码

<?xml version="1.0" encoding="utf-8"?>
<topcont>
<sitenondualtraining>
<title>The Heart of Awakening</title>
<descripition>nondual</descripition>
<link>www.test.com/post/latestpost</link>
</sitenondualtraining>
</topcont>

使用PHP代码

$topcont = new DOMDocument();
$topcont->load("http://fenner.tk/topcont.xml");
$topcont->topcont->sitenondualtraining->title = 'test';
$topcont->sitenondualtraining->descripition = $_POST['nd2'];
$topcont->sitenondualtraining->link = $_POST['nd3'];
$topcont->Save("topcont.xml");

我也试过

$topcont = new SimpleXmlElement('http://fenner.tk/topcont.xml',null, true);
$topcont->sitenondualtraining->title = $_POST['nd1'];
$topcont->sitenondualtraining->descripition = $_POST['nd2'];
$topcont->sitenondualtraining->link = $_POST['nd3'];
$topcont->asXml('topcont.xml');

但这些都不起作用。有人能指出问题在哪里吗?谢谢

文件权限设置为777,但仍不起作用

没有错误,但有警告

Warning: Creating default object from empty value in /home/fenner/public_html/topads.php on line 20
Warning: Creating default object from empty value in /home/fenner/public_html/topads.php on line 21 /home/fenner/public_html/

使用DomDocument,您几乎做到了。你可以这样做:

$topcont = new DOMDocument();
$topcont->load("topcont.xml");

$topcont->getElementsByTagName("title")->item(0)->nodeValue = $_POST['nd2'];
$topcont->getElementsByTagName("description")->item(0)->nodeValue = $_POST['nd2'];
$topcont->getElementsByTagName("link")->item(0)->nodeValue = $_POST['nd3'];
$topcont->save("topcont.xml");

只需记住在存储数据之前对输入进行消毒;)

同样值得研究的是创建cdata部分并使用replaceData,这取决于您打算在每个节点中存储什么。

编辑

作为对下面评论的回应,如果要处理多个子节点,您可能需要稍微更改一下xml结构。这样可以更容易地循环和更新你感兴趣的节点。你会在下面看到,我将"sitenondualtraining"one_answers"siteradiantmind"移动为"item"节点的id,尽管如果这更像你想要的,你可以很容易地将其更改为<site id="nodualtraining>

<?xml version="1.0" encoding="utf-8"?>
<topcont>
<item id="sitenondualtraining">
<title>test</title>
<description>hello test</description>
<link>hello</link>
</item>
<item id="siteradiantmind">
<title>The Heart of Awakening</title>
<description>radiantmind</description>
<link>www.radiantmind.com/post/latestpost</link>
</item>
</topcont>

你的PHP代码会是这样的,同样,这是非常基本的,可以整理,但这是一个好的开始:

$items = $topcont->getElementsByTagName("item");
// loop through each item
foreach ($items as $item) {
$id = $item->getAttribute('id');
// check the item id to make sure we edit the correct one
if ($id == "sitenondualtraining") {
$item->getElementsByTagName("title")->item(0)->nodeValue = $_POST['nd1'];
$item->getElementsByTagName("link")->item(0)->nodeValue = $_POST['nd2'];
$item->getElementsByTagName("description")->item(0)->nodeValue = $_POST['nd3];
}
}

如果你觉得有点冒险,你可以看看xpath和xpath查询,你可以在大多数php文档中找到一些示例代码来帮助你入门,其他用户的评论也会很有帮助。

供参考:getAttribute,getElementsByTagName。

最新更新