gpt4 book ai didi

php - 使用 PHP DOMDocument 时 nextSibling 不起作用

转载 作者:行者123 更新时间:2023-12-04 14:24:02 25 4
gpt4 key购买 nike

我尝试使用 nextSibling 获取以下元素,但以下代码不起作用。
我有一个错误如下
PHP 警告:为第 35 行/php/dom.php 中的 foreach() 提供的参数无效

这一定是由 foreach 循环中的空值引起的。

但是如果我修改它以使用 previousSibling 获取前一个元素,它会按预期工作。

$doc = new DOMDocument();
$html = <<<HTML
<html>
<body>
<ul id="list">
<li>Foo</li>
<li>Bar</li>
</ul>
<h2 class = 'test'>heading2</h2>
<ul id="list2">
<li>list1</li>
<li>list2</li>
</ul>
</body>
</html>
HTML;

$doc ->loadHTML($html);

$DOMNodelist = $doc->getElementsByTagName('*');

foreach($DOMNodelist as $node) {
if ($node -> hasAttribute('class')) {
foreach($node -> nextSibling ->childNodes as $morenodes) {
print_r($morenodes);
}
}
}

最佳答案

因为您的文档有空格分隔元素,所以您实际上需要使用:nextSibling->nextSibling或者,按照我的方式,因为您已经从 '*' 为所有元素生成了一个列表,我将其写为:

foreach($DOMNodelist as $i=>$node) {
if ($node -> hasAttribute('class')) {
foreach($DOMNodelist->item($i+1)->childNodes as $morenodes) {
print_r($morenodes);
}
}
}

或者您可以从文档中删除空格:
$html = <<<HTML
<html><body><ul id="list"><li>Foo</li><li>Bar</li></ul><h2 class = 'test'>heading3</h2><h3>heading3</h3><ul id="list2"><li>list2</li><li>list2</li></ul></body></html>
HTML;

关于php - 使用 PHP DOMDocument 时 nextSibling 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20851106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com