0
在以下代碼中,看似無害的包含空div的腳本標記的引入會導致解析失敗。 (使用一個空的腳本標籤不會造成問題。)$ HTML1被正確解析,檢索兩個範圍的值:爲什麼<script>標籤停止domdocument()解析?
Array
(
[0] => test1
[1] => test2
)
而$ HTML2沒有得到正確解析,僅檢索script標籤之前的跨度:
Array
(
[0] => test1
)
爲什麼會發生這種情況?打開錯誤時,出現兩個錯誤:「意外結束標記:腳本」和「意外結束標記:div」,但我不知道這些意外的原因。
<?php
$html1 = <<<EOT
<div class="productList">
<span>test1</span>
<div></div>
<span>test2</span>
</div>
EOT;
$html2 = <<<EOT
<div class="productList">
<span>test1</span>
<script>
<div></div>
</script>
<span>test2</span>
</div>
EOT;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadhtml($html1);
$xpath = new DOMXPath($dom);
$titles_nodeList = $xpath->query('//div[@class="productList"]/span');
foreach ($titles_nodeList as $title) {
$titles[] = $title->nodeValue;
}
echo("<p>titles without script tag and div</p>");
echo("<pre>");
print_r($titles);
echo("</pre>");
unset($titles);
$dom->loadhtml($html2);
$xpath = new DOMXPath($dom);
$titles_nodeList = $xpath->query('//div[@class="productList"]/span');
foreach ($titles_nodeList as $title) {
$titles[] = $title->nodeValue;
}
echo("<p>titles with script tag and div</p>");
echo("<pre>");
print_r($titles);
echo("</pre>");
?>
您可能會發現有用的在這個問題上的東西:DOM解析器,允許HTML5風格
訣竅很簡單,用一個條件改變
loadHTML
到loadXML
,HTML字符串必須始終合式
來源
2011-09-14 05:14:46 ajreal