从csv文件中删除空白行并使用PHP保存


Deleting blank rows from a csv file and saving it using PHP

我有一个包含40031行的csv文件。我必须删除文件中所有的空白行。在这里,我已经为第13行到第40行编写了一些PHP代码,但它不起作用。问题出在哪里?

我的PHP代码:

<?php 
function del_blank_row($filename, $startrow, $endrow){
    $status = 0;
    //check if file exists
    if (file_exists($filename)) {
        //end execution for invalid startrow or endrow
        if ($startrow < 0 || $endrow < 0 || $startrow > 0 && $endrow > 0 && $startrow > $endrow) {
            die('Invalid startrow or endrow value');
        }
        $updatedcsv = array();
        $count = 0;
        //open file to read contents
        $fp = fopen($filename, "r");
        //get file contents in an array
        $csvcontents = fgetcsv($fp);
        //for every row
        foreach ($csvcontents as $csvcontent) {
            if (!empty($csvcontent)) {
                array_push($updatedcsv, $csvcontent);
                continue;
            }
        }
        print_r($updatedcsv);
        $fp = fopen($filename, "w");
        fputcsv($fp, $updatedcsv);
        fclose($fp);
    } else {
        die('File does not exist');
    }
}
//-----call-----//
$csvdata=del_blank_row('h.csv', 13, 48);

首先以读取模式关闭文件,然后以写入模式打开!即在$fp = fopen($filename, "w"); 之前放入fclose($fp);语句