![](/img/trans.png)
[英]PHP: DOMDocument loadHTML returns an error when using HTML5 tags
[英]PHP DOMDocument loadHTML returns two HTML childNodes
我在Visual Studio中運行PHP,並希望遍歷HTML字符串中的各個節點。 我使用loadHTML將字符串加載到DOMDocument中,並從文檔中提取了firstChild,檢查它是一個HTML節點,但是該節點沒有任何子節點。
然后,我修改了代碼以遍歷文檔的所有childNode,令我驚訝的是,它返回了兩個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之后的輸出顯示節點類型 ,第一個是10,這是DOMDocumentType節點( <!DOCTYPE html PUBLIC "-//W3...
),然后第二個是類型1,即XML_ELEMENT_NODE
<html>
標記。
當您使用loadHTML
-這將始終嘗試創建有效的HTML文檔-這包括添加文檔類型以及普通HTML頁面中所需的<html>
標記等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.