这是我的代码,用于查找注释并写入文件并正常工作。
$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]));
}
问题是即使我在foreach之外file_put_contents
,结果也是正确的。 $ 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]));
答案 0 :(得分:0)
如果您删除了foreach
,该怎么办?在你当前的例子中,你迭代它,所以如果它找到了至少1个孩子,$comments
保持它从foreach
做的最后一次迭代中填充的最后一个值。如果您完全删除foreach
,则$comments
将不再可用。