这是我查找评论并写入文件并正常工作的代码。
$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]));