您可以强制 SimpleXML 进行修剪all当它读取文件时,通过传递空格LIBXML_NOBLANKS
选项simplexml_load_file
:
$sXML = simplexml_load_file('file.xml', null, LIBXML_NOBLANKS);
然后当你打电话时->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>
要根据剩余结构重新生成空格,您需要使用 DOM 而不是 SimpleXML - 但这很容易做到,无需更改任何现有代码,因为dom_import_simplexml http://php.net/dom_import_simplexml只是“重新包装”XML,而不重新解析它。
然后你可以使用the DOMDocument formatOutput财产 http://php.net/manual/en/class.domdocument.php#domdocument.props.formatoutput and save() method http://php.net/manual/en/domdocument.save.php“漂亮地打印”文档:
$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');