到底LIBXML_NOBLANKS是做什么的?

时间:2020-09-14 22:15:41

标签: php xml-parsing html-parsing libxml2

两者之间有什么区别

$domd=new DOMDocument();
$domd->loadHTML($html, LIBXML_NOBLANKS);

$domd=new DOMDocument();
$domd->loadHTML($html, 0);

编辑:以防万一有人要删除所有空白字符(这与LIBXML_NOBLANKS完全不一样)的功能,这是一个功能,

$removeAnnoyingWhitespaceTextNodes = function (\DOMNode $node) use (&$removeAnnoyingWhitespaceTextNodes): void {
    if ($node->hasChildNodes()) {
        // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated;
        // that's why i don't use foreach() - don't change it (unless you know what you're doing, ofc)
        for ($i = $node->childNodes->length - 1; $i >= 0; --$i) {
            $removeAnnoyingWhitespaceTextNodes($node->childNodes->item($i));
        }
    }
    if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && (strlen(trim($node->textContent)) === 0)) {
        //echo "Removing annoying POS";
        // var_dump($node);
        $node->parentNode->removeChild($node);
    } //elseif ($node instanceof DOMText) { echo "not removed"; var_dump($node, $node->hasChildNodes(), $node->hasAttributes(), trim($node->textContent)); }
};
$dom=new DOMDocument();
$dom->loadHTML($html);
$removeAnnoyingWhitespaceTextNodes($dom);

1 个答案:

答案 0 :(得分:1)

LIBXML_NOBLANKS解析器选项将删除仅包含空格的所有文本节点。请考虑以下文档,例如:

<doc>
    <elem>text</elem>
</doc>

通常,元素doc具有三个子元素:一个空白文本节点,一个元素elem和另一个空白文本节点。使用LIBXML_NOBLANKS进行解析时,doc元素将只有一个子元素。