I have a website here that writes info to and XML file, here is my code:
<?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? How do I go about doing this? I have researched the replaceChild method but can not get the syntax quite right. Can anyone please show me?
Or is there a way I can add in there to load a blank xml every time? So it just adds the content to a new XML file?
Thanks so much in advance!
You need a pointer to the node you’re trying to replace if you want to use
replaceChild(). On the other hand, if the idea is to replace all of the data, why read the existing file?This new document will overwrite the previous one. You can get more info here.