使用PHP删除XML元素

时间:2015-12-06 09:48:18

标签: php xml

我想在某些条件下删除XML文件的元素:

的example.xml:

<all>
- <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
- <item>
  <ProductID>51151</ProductID> 
  <Price1>20</Price1> 
  </item>
</all>

PHP:

<?php
$xml = simplexml_load_file('example.xml');
foreach ($xml->item as $item) {
$price  = $item->Price1;
if ($price < 50 ) { REMOVE THIS ITEM  } 
}
$xml->asXML("result.xml");
?>

如果价格低于50,我想要删除这个项目

result.xml为:

<all>
- <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
</all>

2 个答案:

答案 0 :(得分:1)

您正在寻找removeChild中的DOM extension

使用dom_import_simplexml(),您可以将SimpleXMLElement转换为DOMElement。

<?xml version="1.0"?>
<all>
 <item>
  <ProductID>46121</ProductID> 
  <Price1>50</Price1> 
  </item>
</all>

输出(实时here

String

答案 1 :(得分:0)

合并xpath<item>选择所有需要的unset,以从<item>对象中移除SimpleXml

$xml = simplexml_load_string($x); // assume XML in $x
$items = $xml->xpath("/all/item[Price1 < 50]");
foreach ($items as $i) unset($i[0]);

使用

检查结果
echo $xml->asXML();

评论:

  • xpath表达式很简单,[]包含条件。 xpath会将SimpleXml元素数组返回$items
  • 要删除节点,我使用 self-reference-technique 作为discussed many times on SO

看到它有效:https://eval.in/481413