Home > Net >  Remove a child with a specific attribute, in SimpleXMLElement [PHP]
Remove a child with a specific attribute, in SimpleXMLElement [PHP]

Time:07-11

I load an XML file $xml=simplexml_load_file("productsXML.xml", 'SimpleXMLElement', LIBXML_NOCDATA); Then i want to delete the items that have a price lower than 16

foreach($xml as $item) {
    $item->suggested_price = $item->suggested_price  / 1.24;
    $timh = (int) $item->suggested_price;
    if ($timh < 16) {
      //deleting the specific $item
    }
}

After that, i recreate the XML with new DOMDocument

I ve tried lots of solutions in the internet without success. I can manipulate the under-16 prices or print them, but i can't somehow delete the whole $item.

XML SAMPLE

<?xml version="1.0" encoding="UTF-8"?>
  <products>
    <product id="25">
      <name><![CDATA[test]]></name>
      <name_en><![CDATA[test_en]]></name_en>
      <modified>2020-06-29T08:45:09 03:00</modified>
      <suggested_price>84.5</suggested_price>

CodePudding user response:

$doc = new DOMDocument; 
$doc->load('YourFile.xml');

$thedocument = $doc->documentElement;
$thedocument->removeChild(YourItem);

Can you show the code which u try?

You can Edit the Price right? then you propably need to Remove Parent!?

CodePudding user response:

You can use dom_import_simplexml and note that you are converting $item->suggested_price to an int:

$xml = simplexml_load_file("productsXML.xml", 'SimpleXMLElement', LIBXML_NOCDATA);

foreach ($xml as $item) {
    $item->suggested_price = $item->suggested_price / 1.24;
    if ((int) $item->suggested_price < 16) {
        $dom = dom_import_simplexml($item);
        $dom->parentNode->removeChild($dom);
    }
}
  • Related