foreach循环没有';t继续执行


foreach loop doesn't continue to execute

我有一个代码,它只删除过期的xml标记并列出其他标记,但如果一个标记过期,它将删除它并停止foreach循环执行,而不列出其他标记。如果我在代码完成删除过期标签后重新加载页面,它会正常列出其他标签,不会有任何问题。我如何使它继续列出其他标签
php代码:

$xml_file = simplexml_load_file("xml_file.xml");
            foreach ($xml_file as $item)
                {
                    $current_date = time();
                    $article_date = (int)$item->date;
                    $item_number = (int)str_replace("a" , "" ,$item->getName());
                    if ($current_date >= $article_date + 100000)
                        {
                            if ($item->children()->getName() == "a")
                                {
                                    $dom = dom_import_simplexml($item);
                                    $dom->parentNode->removeChild($dom);
                                    $return = simplexml_import_dom($dom);
                                    $xml_file->asXML('xml_file.xml');
                                    unlink('file.html');
                                }
                        }
                    elseif ($current_date < $article_date + 100000)
                        {
                            echo 'hello';
                        }
                }

xml代码:

<articles>
<a1><a>gr</a><date>14</date></a1>
<a2><a>gr</a><date>1414141414141414</date></a2>
<a3><a>gr</a><date>1414141414141414</date></a3></articles>

这段代码应该删除第一个标记并打印两次hello,但它只删除了第一个标记,并停止foreach循环执行,而不打印任何东西,如果我在删除第一个标签后重新加载页面,它会打印两次hello,而不会有任何问题。

有些行由于目的不明确而被注释。。。你可以移除,但不能使用foreach循环,你必须从头开始。。。否则,这就像把椅子移到你自己下面一样——循环不清楚,是应该从"新"$项目开始,还是跳过它。

$children = $xml_file->children(); 
for($i = count($children) - 1; $i >= 0; $i--)
{ 
  $item = $children[$i];
  $current_date = time();
  $article_date = (int)$item->date;
  $item_number = (int)str_replace("a" , "" ,$item->getName());
  if ($current_date >= $article_date + 100000)
  {
     if ($item->children()->getName() == "a")
     {
       $dom = dom_import_simplexml($item);
       $dom->parentNode->removeChild($dom);
      //  $return = simplexml_import_dom($dom);
      //  $xml_file->asXML('xml_file.xml');
      //  unlink('file.html');
     }
  }
  elseif ($current_date < $article_date + 100000)
  {
     echo 'hello';
  }
}
var_dump($xml_file);

另一种删除子项而不转换为DOM的方法是

$children = &$xml_file->children();
// the rest is the same, but replace
// $dom = dom_import_simplexml($item);
// $dom->parentNode->removeChild($dom);
// with
unset($children[$i]);