PHP Simple XML删除所有子级 [英] PHP Simple XML remove all Children
问题描述
我想在再次填充它之前从xml文件中删除所有子项(或创建一个更新,但这似乎要困难得多)。所以我所做的是
i want to remove all children from my xml file before i fill it up again (or create an update but that seemed alot harder). So what i did is
$file = "data.xml";
$xml=simplexml_load_file($file);
$teller=0;
foreach( $entries as $entry ) {
foreach ($xml->xpath('//concerts') as $desc) {
if($teller == 0)
{
$lol=$desc->children();
unset($lol);
}
$concert = $desc->addChild( 'concert' );
$concert->addChild( 'artist', array_shift( $entry ) );
$concert->addChild( 'location', array_shift( $entry ) );
$concert->addChild( 'date', array_shift( $entry ) );
$teller++;
}
}
file_put_contents($file, $xml->asXML());
但这不会删除任何内容,关于我做错了什么主意吗?
But this doesn't remove anything, any ideas on what i did wrong?
推荐答案
这里是一种可能的解决方案(在线演示):
Here is one possible solution (online demo):
$xml = <<< XML
<?xml version='1.0' encoding='utf-8'?>
<concerts>
<concert>
<artist></artist>
<date></date>
</concert>
</concerts>
XML;
$concerts = simplexml_load_string($xml);
foreach ($concerts->xpath('/*/concert/*') as $child)
{
unset($child[0]);
}
echo $concerts->asXML();
标记此CW,因为如何删除元素已在我提供的closevote中给出,并且此答案仅对此进行扩展。现在,已经对此进行了编辑,显示了 自引用方法以删除SimpleXML元素节点, 在PHP的SimpleXML中删除具有特定属性的孩子 a>也可能是重复的。
Marking this CW because how to delete elements is given in my supplied closevote and this answer only expands on this. And this now has been edited showing the self-reference method to delete a SimpleXML element node as outlined in an answer of the question "Remove a child with a specific attribute, in SimpleXML for PHP" which is also a possible duplicate.
这篇关于PHP Simple XML删除所有子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!