简体   繁体   English

XML DOM replaceChild

[英]XML DOM replaceChild

I have a website here that writes info to and XML file, here is my code: 我在这里有一个将信息写入XML文件的网站,这是我的代码:

<?php
$doc = new DOMDocument();
$doc->load("xml/latestContent.xml");
$rootElement = $doc->documentElement;

// Create latestpic element as a child of the root element
$latestPicElement = $rootElement->appendChild($doc->createElement("latestpic"));
$latestPicElement->appendChild($doc->createElement("item", "Latest Pic"));
$latestPicElement->appendChild($doc->createElement("content", $latestPic));

// Create latestvideo element as a child of the root element
$latestVidElement = $rootElement->appendChild($doc->createElement("latestvideo"));
$latestVidElement->appendChild($doc->createElement("item", "Latest Video"));
$latestVidElement->appendChild($doc->createElement("content", $videoData));

// Create latestfact element as a child of the root element
$latestFactElement = $rootElement->appendChild($doc->createElement("latestfact"));
$latestFactElement->appendChild($doc->createElement("item", "Latest Fact"));
$latestFactElement->appendChild($doc->createElement("content", $factData));

// Save back to XML file
$doc->save("xml/latestContent.xml");
?>

The problem here is every time I load the webpage it reloads this function which just adds the same data back onto the XML file, I would like it to replace the original data if I can? 这里的问题是每次我加载网页时都会重新加载此功能,该功能只是将相同的数据添加回XML文件中,如果可以的话,我希望它替换原始数据吗? How do I go about doing this? 我该怎么做呢? I have researched the replaceChild method but can not get the syntax quite right. 我已经研究了replaceChild方法,但语法不正确。 Can anyone please show me? 谁能告诉我?

Or is there a way I can add in there to load a blank xml every time? 还是有一种方法可以添加到其中以每次加载空白xml? So it just adds the content to a new XML file? 因此,它只是将内容添加到新的XML文件中吗?

Thanks so much in advance! 非常感谢!

You need a pointer to the node you're trying to replace if you want to use replaceChild() . 如果要使用replaceChild()则需要一个指向要替换的节点的指针。 On the other hand, if the idea is to replace all of the data, why read the existing file? 另一方面,如果要替换所有数据,为什么要读取现有文件?

//$doc->load("xml/latestContent.xml"); not needed
$rootElement = $dom->appendChild($doc->createElement("Root"));

This new document will overwrite the previous one. 此新文档将覆盖前一个文档。 You can get more info here . 您可以在此处获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM