I have been asking a bit about PHP and XML here at StackOverflow and are getting the grasp of it thanks to all your coders, but sometimes I get stuck.
I want to be able to delete a Node if two children is set correct? I have been trying with this:
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<game id="86102">
<opponent>shoooorty</opponent>
<oppid>2512</oppid>
<lastdraw>2</lastdraw>
<turn>1</turn>
<image>noimage.png</image>
<nextdraw>6198</nextdraw>
<infopop>0</infopop>
<playertilesum>73</playertilesum>
<oppnation>0</oppnation>
</game>
<game id="88341">
<opponent>Jmemek</opponent>
<oppid>1917</oppid>
<lastdraw>3</lastdraw>
<turn>2</turn>
<image>1917a.png</image>
<nextdraw>3107</nextdraw>
<infopop>1</infopop>
<playertilesum>27</playertilesum>
<oppnation>0</oppnation>
</game>
<game id="88382">
<opponent>Gitteloven</opponent>
<oppid>3153</oppid>
<lastdraw>1</lastdraw>
<turn>1</turn>
<image>noimage.png</image>
<nextdraw>2953</nextdraw>
<infopop>1</infopop>
<playertilesum>19</playertilesum>
<oppnation>0</oppnation>
</game>
</data>
');
// original
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
$opNodes = $xml->getElementsByTagName('turn');
$opNodes2 = $xml->getElementsByTagName('infopop');
foreach($opNodes as $node){
$xmlTurn = trim($node->nodeValue);
foreach($opNodes2 as $node2){
$xmlPopup = trim($node2->nodeValue);
if($xmlTurn < 2 && $xmlPopup == 1){
$gameNode = $node->parentNode;
$gameNode->parentNode->removeChild($gameNode);
}
}
}
echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
I want to delete all the games where turn is below 2 and infopop = 1. In this case It should delete the last game… But it doenst work??? What am I doing wrong?
Thanks in advance!
Personally, I have found using SimpleXML much easier than the DOMDocument when dealing with XML in PHP. However, here’s now you’ll make your code work. 🙂