PHP is not my world so, I need some help to update a xml file.
It’s my first time with DOM and seems to not replace the element.
Here’s my XML:
<?xml version="1.0" encoding="utf-8"?>
<feedback>
<feed id="0">
<title>some title</title>
<desc><![CDATA[some text]]></desc>
</feed>
<feed id="1">
<title>some title</title>
<desc><![CDATA[some text]]></desc>
</feed>
<feed id="2">
<title>some title</title>
<desc><![CDATA[some text]]></desc>
</feed>
</feedback>
And PHP code:
<?php
if ($_POST['agg']) {
$selid = $_POST['selectedfeed'];
$newtitolo = $_POST['title'];
$newdesc = nl2br($_POST['feed']);
$file = "feedback.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
$root = $xml->documentElement;
$oldfeed = $root->getElementsByTagName("feed")->item($selid);
$title = $xml->createElement("title");
$titleText = $xml->createTextNode($newtitle);
$title->appendChild($titleText);
$desc = $xml->createElement("desc");
$descText = $xml->createCDATAsection($newdesc);
$desc->appendChild($descText);
$feed = $xml->createElement("feed");
$feed->appendChild($title);
$feed->appendChild($desc);
$root->replaceChild($feed,$oldfeed);
$xml->saveXML("feedback.xml");
}
?>
For the code above, I need to get a “feed” node with a specific ID and replace the feed’s content with the new created elements “title” and “desc” (cdata).
How can I do this?
Almost every thing in your code is Ok.
Just change:
to