本文介绍了使用PHP DOMDocument时nextSibling不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 nextSibling 获取以下元素,但以下代码无效。
我在
PHP下遇到错误,警告:第35行的/php/dom.php中为foreach()提供了无效的参数

I tried to get a following element using nextSibling and the following code doesn't work.i've got an error as belowPHP Warning: Invalid argument supplied for foreach() in /php/dom.php on line 35

必须由foreach循环中的空值引起。

that must be caused by the null value in the foreach loop.

但是如果我使用 previousSibling 可以正常工作。

but if I modify it to get the previous element using previousSibling it works as expected.

$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

或者,我会这样做,因为您已经有了一个'*'生成的所有元素的列表,我将其写为:

Because your document has whitespace separating the elements, you'd actually need to use:
nextSibling->nextSibling
Or, the way I'd do it, because you already have a list generated from '*' for all the elements, I'd write it as:

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

或者您也可以删除文档中的空白:

Or you can just remove the whitespace from the document:

$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 DOMDocument时nextSibling不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:40