0

这是我查找评论并写入文件并正常工作的代码。

$comment1 = $xpath->query('//*[comment() = "abc"]');
$comment2 = $xpath->query('//*[comment() = "cde"]');

$commentIterator = new MultipleIterator();
$commentIterator->attachIterator(new IteratorIterator($comment1));
$commentIterator->attachIterator(new IteratorIterator($comment2));

foreach ($commentIterator as $comments) {
    file_put_contents('page1.php', $dom->saveHTML($comments[0]));
    file_put_contents('page2.php', $dom->saveHTML($comments[1]));   
}

问题是即使我file_put_contents在 foreach 之外,结果也是正确的。$comments 是循环内的局部变量。我需要foreach吗?

此代码与 foreach 外部的 $comments 一样有效

$comment1 = $xpath->query('//*[comment() = "abc"]');
$comment2 = $xpath->query('//*[comment() = "cde"]');

$commentIterator = new MultipleIterator();
$commentIterator->attachIterator(new IteratorIterator($comment1));
$commentIterator->attachIterator(new IteratorIterator($comment2));

foreach ($commentIterator as $comments) {

}

file_put_contents('page1.php', $dom->saveHTML($comments[0]));
file_put_contents('page2.php', $dom->saveHTML($comments[1]));   
4

1 回答 1

0

如果在您的情况下您删除了foreach? 在您当前的示例中,您对其进行迭代,因此如果它找到了至少 1 个孩子,$comments则保留它从上一次迭代中填充的最后一个值foreach。如果您foreach完全删除您的,$comments将不再可用。

于 2013-04-25T13:47:43.367 回答