无法在 XML 文件上 insertBefore [英] Unable to insertBefore on an XML file

查看:29
本文介绍了无法在 XML 文件上 insertBefore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本来更新 RSS XML 文件.我希望它采用现有文件并将新项目添加到项目列表的顶部.我之前已经将它添加到文件的末尾,但现在它目前根本没有添加新项目.我一直在网上检查,但我仍然无法让它工作.这是我目前所拥有的:

I'm trying to write a script that will update an RSS XML file. I want it to take the existing file and add a new item to the top of the items list. I've previous gotten it to add to the end of the file, but now it's currently not adding the new item at all. I've been checking around online, but I still can't get it to work. Here is what I have so far:

$rssDoc = new DOMDocument();
$rss_file = $_SERVER['DOCUMENT_ROOT'].'/test_site/feed.xml';
$rssDoc->load($rss_file);
$items = $rssDoc->getElementsByTagName('item');

$newItem = $rssDoc->createElement('item');
$rssTitle = $rssDoc->createElement('title');
$rssTitle->appendChild($rssDoc->createTextNode($title));
$newItem->appendChild($rssTitle);

$rssDesc = $rssDoc->createElement('description');
$rssDesc->appendChild($rssDoc->createTextNode($string));
$newItem->appendChild($rssDesc);

$rssLink = $rssDoc->createElement('link');
$rssLink->appendChild($rssDoc->createTextNode($link));
$newItem->appendChild($rssLink);

$rssDate = $rssDoc->createElement('pubDate');
$rssDate->appendChild($rssDoc->createTextNode($pubDate));
$newItem->appendChild($rssDate);

$firstItem = $items->item(0);
$firstItem->insertBefore($newItem,$firstItem->firstChild);

$rssDoc->formatOutput = true;
echo $rssDoc->saveXML();

我错过了什么?

推荐答案

我搞定了.我改变了这些行:

I got it working. I changed these lines:

$firstItem = $items->item(0);
$firstItem->insertBefore($newItem,$firstItem->firstChild);

到这一行:

$items->item(0)->parentNode->insertBefore($newItem,$items->item(0));

这篇关于无法在 XML 文件上 insertBefore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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