使用PHP从节点中删除与XML中的特定字符串匹配的所有元素

问题描述 投票:0回答:2

我需要使用PHP删除一些与XML上的特定字符串匹配的元素,我想我可以使用DOM执行此操作,因为我一直在阅读。问题是使用多个字符串。

我有这个XML:

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <reference>00001</reference>
    <other_string>PRODUCT 1</other_string>
    <brand>BRAND 1</brand>
  </item>
  <item>
    <reference>00002</reference>
    <other_string>PRODUCT 2</other_string>
    <brand>BRAND 2</brand>
  </item>
  <item>
    <reference>00003</reference>
    <other_string>PRODUCT 3</other_string>
    <brand>BRAND 3</brand>
  </item>
  <item>
    <reference>00004</reference>
    <other_string>PRODUCT 4</other_string>
    <brand>BRAND 4</brand>
  </item>
  <item>
    <reference>00005</reference>
    <other_string>PRODUCT 5</other_string>
    <brand>BRAND 5</brand>
  </item>
</products>

我需要删除与<brand></brand>标记上的字符串“BRAND 3和BRAND 4”匹配的元素,并获取与此类似的XML

<?xml version="1.0" encoding="utf-8"?>
<products>
  <item>
    <reference>00001</reference>
    <other_string>PRODUCT 1</other_string>
    <brand>BRAND 1</brand>
  </item>
  <item>
    <reference>00002</reference>
    <other_string>PRODUCT 2</other_string>
    <brand>BRAND 2</brand>
  </item>
  <item>
    <reference>00005</reference>
    <other_string>PRODUCT 5</other_string>
    <brand>BRAND 5</brand>
  </item>
</products>

任何帮助将受到高度赞赏。

php xml dom simplexml
2个回答
0
投票

最难的部分是删除元素。因此,你可以看看this answer

首先获得所有品牌与xPath('//brand')。然后删除与您的过滤规则匹配的项目。

$sXML = simplexml_load_string($xml);
$brands = $sXML->xPath('//brand');

function filter(string $input) {
    switch ($input) {
        case 'BRAND 3':
        case 'BRAND 4':
            return true;
        default:
            return false;
    }
}

array_walk($brands, function($brand) {
    $content = (string) $brand;
    if (filter($content)) {
        $item = $brand->xPath('..')[0];
        unset($item[0]);
    }
});

var_dump($sXML->asXML());

1
投票

再次使用XPath,但这次使用它来过滤你之后的节点,然后删除它们......

$xml = simplexml_load_file("data.xml");

$remove = $xml->xpath("//item[brand='BRAND 3' or brand='BRAND 4']");
foreach ( $remove as $item )    {
    unset($item[0]);
}

XPath //item[brand='BRAND 3' or brand='BRAND 4']只是寻找任何<item>元素,它有一个包含BRAND 3或BRAND 4的<brand>元素。然后循环匹配并删除它们。使用$item[0]是一种软件来取消设置XML元素,而不是取消设置正在使用的变量。

© www.soinside.com 2019 - 2024. All rights reserved.