【问题标题】:Remove all elements from XML that match specific strings in a node with PHP使用 PHP 从 XML 中删除与节点中的特定字符串匹配的所有元素
【发布时间】:2019-08-06 23:24:22
【问题描述】:

我需要使用 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>

并且我需要删除与&lt;brand&gt;&lt;/brand&gt; 标记上的字符串“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>

我们将不胜感激。

【问题讨论】:

  • 使用 xpath 获取所有 brand 标签。根据您的过滤规则检查他们的内容。如果它们匹配,请转到 item 并删除该项目

标签: php xml dom simplexml


【解决方案1】:

最难的部分是移除元素。因此你可以看看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());

【讨论】:

  • 这很完美,但是这有一个空格问题,因为代码留下了一个元素被删除的地方。我正在努力解决它。谢谢! @kuh-chan
【解决方案2】:

再次使用 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'] 只是在寻找任何 &lt;item&gt; 元素,该元素具有包含 BRAND 3 或 BRAND 4 的 &lt;brand&gt; 元素。然后循环匹配并删除它们。使用 $item[0] 是取消设置 XML 元素而不是取消设置正在使用的变量的一种手段。

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多