Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么标记会停止domdocument()解析?_Php_Domdocument - Fatal编程技术网

Php 为什么标记会停止domdocument()解析?

Php 为什么标记会停止domdocument()解析?,php,domdocument,Php,Domdocument,在下面的代码中,看似无害地引入包含空div的脚本标记会导致解析失败。使用空脚本标记不会导致任何问题$html1被正确解析,检索两个跨度的值: Array ( [0] => test1 [1] => test2 ) 然而$html2没有得到正确的解析,只检索脚本标记前面的跨度: Array ( [0] => test1 ) 为什么会发生这种情况?打开errors后,我得到两个错误,Unexpected end tag:script和Unexpected

在下面的代码中,看似无害地引入包含空div的脚本标记会导致解析失败。使用空脚本标记不会导致任何问题$html1被正确解析,检索两个跨度的值:

Array
(
    [0] => test1
    [1] => test2
)
然而$html2没有得到正确的解析,只检索脚本标记前面的跨度:

Array
(
    [0] => test1
)
为什么会发生这种情况?打开errors后,我得到两个错误,Unexpected end tag:script和Unexpected end tag: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>");

?>

div不属于脚本标记内部。Javascript属于脚本标记内部


将div从script标记中去掉,就可以了。

诀窍很简单,只需满足一个条件即可将loadHTML更改为loadXML, HTML字符串必须始终格式良好


我的问题是我无法控制要解析的html,而这个html在脚本中包含div。我想知道,让它工作的唯一方法是否是使用类似于在解析之前用正则表达式删除脚本的hack。在这个问题中,您可能会发现一些有用的东西:。@Paul DelRe确实,这看起来像是相同的问题,他通过使用不同的DOM解析器解决了这个问题。我想我的选择是这样做还是仅仅使用正则表达式来删除脚本。
$dom->loadXML($html2);