Fer*_*era 4 php xml arrays simplexml filter
我一直在搜索信息,当我将 PHP 代码导出为 XML 时,如何删除它留下的标签值之间的空格,我将详细解释,首先我加载和 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
?>
Run Code Online (Sandbox Code Playgroud)
这是原始的 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>
Run Code Online (Sandbox Code Playgroud)
脚本的输出发送:
<?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>
Run Code Online (Sandbox Code Playgroud)
正如您在输出中看到的那样,产品 2 和产品 5 之间有一个空白区域,我需要将其删除。任何帮助将不胜感激。
您可以强制 SimpleXML在读取文件时修剪所有空格,方法是将LIBXML_NOBLANKS选项传递给simplexml_load_file:
$sXML = simplexml_load_file('file.xml', null, LIBXML_NOBLANKS);
Run Code Online (Sandbox Code Playgroud)
然后,当您调用 时->asXML(),所有空格都将被删除,您将在一行中获得 XML,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<products><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></products>
Run Code Online (Sandbox Code Playgroud)
要根据剩余的结构重新生成空白,您需要使用 DOM 而不是 SimpleXML——但这很容易做到,而无需更改任何现有代码,因为dom_import_simplexml只需“重新包装”XML 而无需重新解析它。
然后你可以使用的DOMDocument formatOutput属性和save()方法,以“漂亮打印”的文件:
$sXML = simplexml_load_file('file.xml', null, LIBXML_NOBLANKS);
// ...
// process $sXML as before
// ...
$domDocument = dom_import_simplexml($sXML)->ownerDocument;
$domDocument->formatOutput = true;
echo $domDocument->save('filtered.xml');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2596 次 |
| 最近记录: |