Trying to make an API for currency conversion,
Need to select a specific currency and delete it from the xml file...
XML file looks like this:
<currencies>
<currency>
<ccode>CAD</ccode>
<cname>Canadian Dollar</cname>
<cntry>Canada</cntry>
</currency>
<currency>
<ccode>CHF</ccode>
<cname>Swiss Franc</cname>
<cntry>Liechtenstein, Switzerland</cntry>
</currency>
<currency>
<ccode>CNY</ccode>
<cname>Yuan Renminbi</cname>
<cntry>China</cntry>
</currency>
...etc
I need to use php to select and delete the specific currency, at the moment trying this:
<?php
$dom = new DOMDocument("1.0", "utf-8");
$dom->load('data/ccodes.xml');
$nodes = $dom->getElementsByTagName("currencies");
foreach ($nodes as $n){
if($n->getAttribute("ccode") == "CAD") {
$parent = $n->parentNode;
$parent->removeChild($n);
}
}
echo $dom->saveXML();
?>
But It's not working.... I'm pretty sure it's really simple but I have no idea what I'm doing with coding... :/
Need to make it so I can just change CAD to whatever to delete any currency I need to...
Your iterating the root node currencies
but I think you meant to iterate the currency
nodes. ccode
is not an attribute node, but a child element node. Even if you iterate currency
nodes with the correct condition it would still not fully work.
DOMElement::getElementsByTagName()
returns a live result. Inside the loop you modify the DOM and the list is modified as well. You could us a for
loop to iterate it backwards, use iterator_to_array()
to materialize the node list into an array or use Xpath. DOMXpath::evaluate()
returns a node list, but it is not a live result. So the list will not change if you modify the document.
$document = new DOMDocument();
//$document->load('data/ccodes.xml');
$document->loadXml($xml);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('/currencies/currency[ccode="CAD"]') as $node) {
$node->parentNode->removeChild($node);
}
echo $document->saveXML();
Output:
<?xml version="1.0"?>
<currencies>
<currency>
<ccode>CHF</ccode>
<cname>Swiss Franc</cname>
<cntry>Liechtenstein, Switzerland</cntry>
</currency>
<currency>
<ccode>CNY</ccode>
<cname>Yuan Renminbi</cname>
<cntry>China</cntry>
</currency>
</currencies>