douchun1900 2017-09-22 11:48
浏览 53

从PHP中的CSV文件中删除当前的迭代行

I want to delete current iterating row from CSV file, Suppose I have 5 rows (1,2,3,4,5) into my CSV file, I opened my file while iterating the rows one by one using foreach, when it comes to 3rd row then 3rd row should be deleted from CSV file and other 1,2,4,5 rows will be same while same iterration. I don't want to use like Skip the 3rd iterration and save it into another file, not like rename file name. So, Please anyone can help me how to do this in PHP?

Suppose, like SQL command to delete current row, is there anything in PHP?

Thanks.

  • 写回答

1条回答 默认 最新

  • dpgua04022 2017-09-22 12:01
    关注

    You will need to have permissions to write the file. If you remove a row, you will have to save the file. As you do not want to have any empty rows as well, you need to read the whole file.

    I suggest to get the file content, and split it into a array by lines. With the explode function you can split the content by the line break, most likely " ". So an array wich will contain each line of the csv file will be existing. Now you can simply remove the line from the array and create a string out of it, before saveing the changed content back to the csv file.

    // get csv content into string variable
    $csvContent = file_get_contents(__DIR__ . "/yourfile.csv");
    // create array out of csv, limited by PHP_EOL wich determines the systems line break
    // this means, every line in the csv file will be represended by an array key and its value
    $csvArray = explode(PHP_EOL, $csvContent);
    
    // unset the 3th csv line. 
    unset($csvArray[2]); // keep in mind array starts at 0, so third line is array key 2 
    
    // from here on you can manipulate the array $csvArray as you like. 
    // add lines, remove lines or just use the given content for future operations. 
    // you can also iterate over the array with: foreach ($csvArray as $line => $value) {}
    
    // create string out of modified csv array
    $csvContent = implode(PHP_EOL, $csvArray);
    // save result back into the csv file
    file_put_contents( __DIR__ . "/yourfile.csv", $csvContent);
    

    Check implode/explode php function docs:

    http://php.net/manual/en/function.implode.php

    http://php.net/manual/en/function.explode.php

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集