删除节点不适用于简单 XML (PHP)



如果节点的标题与过滤器匹配(数组),我想删除节点。我使用unset(),并且已经尝试了$node$item,但是两个参数都不会删除我的节点...

此代码中有什么问题? - 我确实输入IF条件,因为我在控制台中看到in if

$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 ifnn";
            unset($item);
        }
    }
}
$dom->saveXML();
$dom->save("shop1_2.xml");

XML文件:

<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>

问候,谢谢!

您所做的只是要解开本地变量。相反,您需要更改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 "$titlen";
    if (in_array($title, $titleArray)) {
        $item->parentNode->removeChild($item);
    }
}
$dom->saveXML();
$dom->save("shop1_2.xml");

最新更新