douzuo0002 2012-02-26 13:01
浏览 48
已采纳

PHP Simple XML删除所有Children

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?

  • 写回答

3条回答 默认 最新

  • duanmanmian7589 2012-02-26 14:37
    关注

    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();
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?