我有一个代码,只删除已过期的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>
这段代码应该删除第一个标签并打印两次问候,但是它只是删除第一个标签并停止执行foreach循环而不会打印任何东西,如果我在删除第一个标签后重新加载页面,它会打印两次问候而没有任何问题。
注释了某些行,因为它们的目的不明确...您可以删除,但不能foreach
循环播放,而必须从头开始...否则,这就像将椅子移到自己下面-循环不清楚,是否应该从循环开始“新” $ item,或跳过它。
$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]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句