PHP DOMDocument 加载HTML returns 两个HTML 子节点

PHP DOMDocument loadHTML returns two HTML childNodes

我是 运行 PHP 在 Visual Studio 中,我希望跨过 HTML 字符串中的各个节点。我使用 loadHTML 将字符串加载到 DOMDocument 中,并从文档中提取 firstChild,检查它是一个 HTML 节点,但该节点没有任何子节点。

然后我修改了代码以遍历文档的所有子节点,令我惊讶的是这返回了两个 HTML 节点,第二个节点具有预期的子节点。这是我应该期待的吗,谁能解释为什么?

附上代码和输出。

enter code here
<?php
$html = '<html><head></head><body>';
$html .= '<h1>Content 1</h1><h2>Content 1.1</h2><h3>Content 1.1.1</h3>';
$html .= '</body></html>';

define ('NEWLINE',"\r\n" );

function recurceHTML ($node, $spaces)
{
    $nextIndent = $spaces . '  ';
    print ($spaces . $node->nodeName . NEWLINE);
    foreach($node->childNodes as $childNode)
    {
        recurceHTML ($childNode, $nextIndent);
    }
}


$dom = DOMDocument::loadHTML($html);
$spaces = '  ';

foreach ($dom->childNodes as $child)
{
    recurceHTML ($child, $spaces);
}
$wait = readline();
?>

上面的输出是:

  html
  html
    head
    body
      h1
        #text
      h2
        #text
      h3
        #text

对您的代码进行轻微更新以更清楚地显示它正在使用的内容,您可以看到数据的来源...

function recurceHTML ($node, $spaces)
{
    $nextIndent = $spaces . '  ';
    print ($spaces . $node->nodeName."->".$node->nodeType . NEWLINE);

    if ( $node->nodeType == 1 ) {
        foreach($node->childNodes as $childNode)
        {
            recurceHTML ($childNode, $nextIndent);
        }
    }
}

$dom = new DOMDocument();
$dom->loadHTML($html);
$spaces = '  ';

echo $dom->saveHTML().PHP_EOL;

foreach ($dom->childNodes as $child)
{
    recurceHTML ($child, $spaces);
}

第一个 echo 向您展示了它正在处理的实际文档...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head></head><body><h1>Content 1</h1><h2>Content 1.1</h2><h3>Content 1.1.1</h3></body></html>

如您所见 - 这也将文档类型作为内容的一部分。

然后你有主函数的输出...

  html->10
  html->1
    head->1
    body->1
      h1->1
        #text->3
      h2->1
        #text->3
      h3->1
        #text->3

tagName 后的输出显示 node type, the first one is 10 which is the DOMDocumentType node ( the <!DOCTYPE html PUBLIC "-//W3...), then the second one is type 1 which is XML_ELEMENT_NODE,这是您的 <html> 标签。

作为您使用 loadHTML - 这将始终尝试创建有效的 HTML 文档 - 这包括添加文档类型以及需要的 <html> 标签等在正常的 HTML 页面中。