我正在使用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有关,并且可能会将下一个附加到上一个或者其他内容,但我不知道如何。
以前是否有人遇到过这个问题,或者你能看出我做错了什么吗? 非常感谢帮助!
答案 0 :(得分:1)
我现在解决了。事实证明appendChild
方法会弹出列表中的项目,因此所有元素都会向后移动一个位置。这很有效:
for ( $i=0;$i<$anchs->length;){ // so don't increase $i
$anch=$anchs->item($i);
$container->appendChild($anch);
}