【发布时间】:2019-08-10 16:55:36
【问题描述】:
我一直在搜索信息,当我将 PHP 代码导出到 XML 时,如何删除 PHP 代码留下的标记值之间的空格,我将详细解释,首先我加载和 XML,然后我使用 xPath 对文件进行搜索,然后我删除一些与某些品牌不匹配的元素,最后我将其重新导出为新的 XML,问题是这个新的 XML 充满了代码留下的空白。我试过修剪它,但它似乎不能正常工作。
这是我的代码:
<?php
$sXML = simplexml_load_file('file.xml'); //First load the XML
$brands = $sXML->xPath('//brand'); //I do a search for the <brand> tag
function filter(string $input) { //Then I give it a list of variables
switch ($input) {
case 'BRAND 3':
case 'BRAND 4':
return false;
default:
return true;
}
}
array_walk($brands, function($brand) { //I remove all elements do not match my list
$content = (string) $brand;
if (filter($content)) {
$item = $brand->xPath('..')[0];
unset($item[0]);
}
});
$sXML->asXML('filtred.xml'); // And finally export a new xml
?>
这是原始的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>
脚本的输出会发送这个:
<?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>
正如您在输出中看到的那样,产品 2 和产品 5 之间有一个空格,我需要将其删除。任何帮助将不胜感激。
【问题讨论】:
-
使用
DOM而不是SimpleXML可能会更好,因为它具有正确删除节点的方法。向上遍历到父节点也容易得多
标签: php arrays xml filter simplexml