I have this PHP code that adds a set of nodes to an XML file. It does most of what it should do, it finds where to make the additions, but then it doesn’t make the update.
I have an xml file of this structure.
<COMMUNITIES>
<COMMUNITY ID="c001">
<URLS>
<URL ID="u001">
<NAME>Google.com</NAME>
<URL>http://www.google.com</URL>
</URL>
</URLS>
</COMMUNITY>
</COMMUNITIES>
The updates are being made to the URLS node. The user clicks an “Add URL” link and I add the new URL to this node like this.
<URL ID="u002">
<NAME>Yahoo.com</NAME>
<URL>http://www.yahoo.com</URL>
</URL>
If the URLS node exists, I append the new url node. If the URLS node does not exist, I create it, then append the new url node.
There are no errors, everything seems to work, but the URLS node is empty. Here is the PHP script.
function add_url( $nodeid, $urlid, $urlname, $urllink ) {
$dom = new DOMDocument();
$dom->load('communities.xml');
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
// get document element
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");
if ($nodes->length) {
$node = $nodes->item(0);
$xurl = $dom->createElement("URL");
$xurl->setAttribute("ID", $urlid);
$xuname = $dom->createElement("NAME");
$xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
$xuname->appendChild($xunameText);
$xulink = $dom->createElement("URL");
$xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
$xulink->appendChild($xulinkText);
$xurl->appendChild($xuname);
$xurl->appendChild($xulink);
$xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");
if ($xurls->length) {
}
else {
$xurls = $dom->createElement("URLS");
}
$xurls->appendChild($xurl);
/* $node->appendChild($xurls); */
}
$dom->save('communities.xml');
}
I thought the problem was that I was appending the URLS node when it already existed. But I commented out that line. I am sure the problem is simple, but I am new at this. I looked on the site and did not find that specific situation.
Edit
-
Removed return statement before
if ($xurls->length). -
Fixed function.
The problem was that I was attempting to add nodes to a node which was already in the XML file as empty.
Instead of the node having data like this.
I had a node like this.
Common sense says that this should not be a problem. If the node is empty then appendChild should just add the data and rewrite the node as.
Here is the PHP script that worked. You will note that I created a new node instead of appending to
<URLS/>. I also reordered the appendChild to start from the top node instead of the creating the child nodes first then appending a set of nodes to the top node.So I must modify the function that creates the empty node
<URLS/>. I should not create the node in that function but create it here in the add_url function only when it doesn’t exist.