[英]Remove all elements from XML that match specific strings in a node with PHP
我需要使用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>
任何幫助將不勝感激。
再次使用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']
只是在尋找具有<brand>
元素且包含BRAND 3或BRAND 4的任何<item>
元素。並刪除它們。 使用$item[0]
可以取消XML元素的設置,而不是取消正在使用的變量的設置。
最難的部分是刪除元素。 因此,您可以看看這個答案
首先使用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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.