我在Visual Studio中运行PHP,并希望遍历HTML字符串中的各个节点。我使用loadHTML将字符串加载到DOMDocument中,并从文档中提取了firstChild,检查它是一个HTML节点,但是该节点没有任何子节点。
然后,我修改了代码以遍历文档的所有childNode,令我惊讶的是,它返回了两个HTML节点,第二个具有预期的子节点。这是我应该期待的,任何人都可以解释原因吗?
附带代码和输出。
cy.get('td').eq(1).trigger('mouseover')
上面的输出是:
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();
?>
答案 0 :(得分:1)
稍稍更新一下代码即可更清楚地显示其使用的内容,您可以看到数据来自何处...
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,第一个是10,它是DOMDocumentType节点(<!DOCTYPE html PUBLIC "-//W3...
),然后第二个是类型1,即{{ 3}},即您的<html>
标签。
使用loadHTML
时-始终会尝试创建有效的HTML文档-这包括添加普通HTML页面中需要的文档类型以及<html>
标签等。