为什么 PHP 的 DOMDocument 从处理指令节点中删除前导空格? (<?php ?>)

Why does PHP's DOMDocument remove leading whitespace from Processing Instruction nodes? (<?php ?>)

我正在将 XML 兼容的 PHP 文件加载到 DOM 文档中。

    $domDoc = new DOMDocument();
    $domDoc->recover            = TRUE;
    $domDoc->preserveWhiteSpace = TRUE;
    $domDoc->formatOutput       = FALSE;
    $domDoc->substituteEntities = FALSE;
    $domDoc->resolveExternals   = FALSE;

尽管保留了空格并指示它不格式化输出,但当我用 $domDoc->saveXML() 保存 XML 时,我仍然发现 <?php ?> 块中的前导空格被删除了。

输入:

<?xml version="1.0" encoding="UTF-8"?>
<html>
<?php

// This is code.

// Something else.
    echo 'test';

?>
</html>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<html>
<?php // This is code.

// Something else.
    echo 'test';

?>
</html>

我希望输出与输入尽可能一致。折叠属性之间的空白是可以接受的,但折叠节点之间或处理指令内的空白是不行的。为什么 PHP::DOMDocument() / libxml2 会更改 PI 的内容?我是否需要求助于手动 DOM 回显以保持空白 完全 保留?

领头白space在一个PI节点其实可以崩溃,因为the DOM considers the data portion of a processing instruction to be:

The content of this processing instruction. This is from the first non white space character after the target to the character immediately preceding the ?>.

(强调我的。)

preserveWhiteSpace 设置仅适用于文本节点,这就是为什么它在这里对您没有帮助。

在任何情况下,我建议不要依赖嵌入式 PHP 被视为处理指令,因为 PHP 可以在其中包含 ?>(例如,作为字符串文字的一部分) 这将提前终止处理指令。