I’m developing a web interface that enables admins to ban/unban particular users from my server whose software depends on an XML file to determine ban status of users. Initially, the ‘Bans.xml’ has the following contents.
<Bans version="1.036">
<Nick>
<Ban>
<Overrideable enable="false"/>
<Nick>cray</Nick>
</Ban>
</Nick>
</Bans>
How do I write a php code so that I get the following XML file?
<Bans version="1.036">
<Nick>
<Ban>
<Overrideable enable="false"/>
<Nick>cray</Nick>
</Ban>
<Ban>
<Overrideable enable="false"/>
<Nick>newuser</Nick>
</Ban>
</Nick>
</Bans>
So far I’ve managed to write the following script:
<?php
$xml=new DOMDocument();
$xml->formatOutput=true;
$xml->preserveWhiteSpace=false;
$xml->load("Bans.xml");
$root=$xml->documentElement;
$fnode=$root->firstChild;
$ori=$fnode->childNodes->item(2);
$nick=$xml->createElement("Nick");
$nickText=$xml->createTextNode("newuser");
$nick->appendChild($nickText);
$ban=$xml->createElement("Ban");
$ban->appendChild($nick);
$root->insertBefore($ban,$ori);
header("Content-type:text/xml");
$xml->save('Bans.xml');
?>
But all that the above code gives me is:
<Bans version="1.036">
<Nick>
<Ban>
<Overrideable enable="false"/>
<Nick>cray</Nick>
</Ban>
</Nick>
<Ban>
<Nick>Crayaas</Nick>
</Ban>
</Bans>
——–I’ve managed to add the nodes properly by replacing;———
$root->insertBefore($ban,$ori);
With the following code;
$fnode->insertBefore($ban,$ori);
My one last question is, how do i remove a particular ban, where nick is equal to a user supplied string stored in the variable $buser. I used the following code. But using $buser in the condition creates errors.
$buser="newuser";
$dom=new DOMDocument();
$dom->load('settings/Bans.xml');
$bans=$dom->documentElement;
$xpath=new DOMXpath($dom);
$result=$xpath->query('/Bans/Nick/Ban[Nick="$buser"]');
$result->item(0)->parentNode->removeChild($result->item(0));
header("Content-type: text/xml");
$dom->save('settings/Bans.xml');
Would be glad if this could be answered as well 😉
This:
Should be:
After all,
<Nick>is not the rootnode, but the first child of it