PHP Remove Element from XML

后端 未结 3 2088
故里飘歌
故里飘歌 2021-01-24 03:10

I want to remove tasks that are older than today, but I can\'t quite figure out how to remove elements from XML file yet.

$xml_file = simplexml_load_file(\'file.         


        
3条回答
  •  盖世英雄少女心
    2021-01-24 03:32

    It's actually very tricky. You have to unset() the appropriate variable, but it needs to be a reference to the parent node (i.e., unset($aTask) will not work). Additionally, if you do foreach ($xml_file->task as $index => $aTask) to keep track of the child position, you'll get task in every iteration!

    You need some ugly code like this:

    $index = 0;
    $remove = array();
    foreach ($xml_file->task as $aTask) {
        if ($aTask->date < $today) {
            $remove[] = $index;
        }
        $index++;
    }
    
    foreach($remove as $index){
        unset($xml_file->task[0]);
    }
    

    P.S. As already noted, your date handling routines do not work.

    Edit: I've actually tried my own code and it works, so downvoter should explain himself.

提交回复
热议问题