【问题标题】:php the foreach loop applied to DomNodeList skips an element when appendingphp 应用于 DomNodeList 的 foreach 循环在追加时跳过一个元素
【发布时间】:2015-02-26 01:45:44
【问题描述】:

我正在使用 php 从页面加载元素。它几乎可以工作。唯一的事情是,从我尝试加载的所有锚元素中,它只给了我一半。它跳过每个第二个元素。这是我的一些 php 脚本

$div = @$doc->getElementById('topicList');

$anchs=$div->getElementsByTagName('a');
//echo $anchs->length;  it does have the correct length

$container = $doc->createElement("div");
$container->setAttribute('class', 'relative');


foreach ($anchs as $anch){

$container->appendChild($anch);
}   
       /// /////////
$expDiv = $doc->createElement("div");
$expDiv->setAttribute('class', 'explanation_div');
$container->appendChild($expDiv);
echo utf8_decode(@$doc->saveXML($container));

所以这只会放出每隔一个的锚元素,而不是全部。

我已经尝试过使用 for 循环,但这在 DomNodeList 上是不允许的。

我认为它一定与 appendChild 有关,并且它可能会将下一个附加到前一个或其他东西上,但我不知道如何。

以前有人遇到过这个问题吗,或者你能看出我做错了什么吗? 非常感谢帮助!

【问题讨论】:

    标签: php foreach domdocument appendchild


    【解决方案1】:

    我现在解决了。原来appendChild 方法弹出列表的项目,所以所有元素都向后移动一个位置。这有效:

    for ( $i=0;$i<$anchs->length;){   // so don't increase $i
        $anch=$anchs->item($i);
    
        $container->appendChild($anch);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      • 2012-03-12
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 2022-01-21
      • 2019-02-16
      相关资源
      最近更新 更多