Search code examples
phpxmldomsimplexml

Delete Node isn't working with Simple XML (PHP)


I want to delete a node if the title of an node is matching a filter (array). I use unset() and I already tried $node and $item but both arguments won't delete my node...

What is wrong in this code? - I do enter the if condition, because I see in if in my console!

$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->load("shop1.xml");
$pathXML = "/products/product";
$titleArray = array("Test", "Battlefield 1");


$doc = simplexml_import_dom($dom);

$items = $doc->xpath($pathXML);
foreach ($items as $item) {
    $node = dom_import_simplexml($item);
    $title = $node->getElementsByTagName('title')->item(0)->textContent;
    echo $title . "\n";

    foreach ($titleArray as $titles) {
        echo $titles . "\n";
        if (mb_stripos($title, $titles) !== false) {
            echo "in if\n\n";
            unset($item);
        }
    }
}

$dom->saveXML();
$dom->save("shop1_2.xml");

XML File:

<products>
<product>
    <title>Battlefield 1</title>
    <url>https://www.google.de/</url>
    <price>0.80</price>
</product>
<product>
    <title>Battlefield 2</title>
    <url>https://www.google.de/</url>
    <price>180</price>
</product>
</products>

Greetings and Thank You!


Solution

  • All you're doing is unsetting a local variable. Instead you need to alter the DOM:

    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->load("shop1.xml");
    $xpathQuery = "/products/product";
    $titleArray = array("Test", "Battlefield 1");
    $xp = new DomXpath($dom);
    $items = $xp->query($xpathQuery);
    foreach ($items as $item) {
        $title = $item->getElementsByTagName('title')->item(0)->textContent;
        echo "$title\n";
        if (in_array($title, $titleArray)) {
            $item->parentNode->removeChild($item);
        }
    }
    $dom->saveXML();
    $dom->save("shop1_2.xml");