Remove Blank ROWS from CSV files in php

感情迁移 提交于 2019-12-02 07:06:16
$lines = file("test.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (empty($csv[SPECIFIC_COLUMN])) {
        $num_rows--;
    }
}

If you don't want to check a specific column, but just filter out rows where all columns are empty, change it to:

    if (count(array_filter($csv)) == 0) {

For empty rows:

$lines = file("test.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    $csv = str_getcsv($line);
    if (!array_filter($csv)) {
        $num_rows--;
    }
}
$filename = "test.csv";

if (($fp = fopen($filename, "r")) !== FALSE) { 
    $rows = explode("\n", $fp);
    $csv = "";

    foreach($rows as $r) {
        if(str_replace(array(" ", ","), "", $r) != "")
            $csv .= $r."\n";
    }

    file_put_contents($filename, $csv);;
}

Basically what Barmar already posted, but if you need to process (many) large* files, I'd recommend to give rtrim (or ltrim) a try, since usually those are a bit faster for a task like yours:

$lines = file("test.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$num_rows = count($lines);
foreach ($lines as $line) {
    if (!rtrim($line, ',')) {
        $num_rows--;
    }
}

*By large I mean that large that it's really worth it. Don't waste your time doing micro-optimizations.

use notepad++ to open .csv file. Then search for ^\*s goto find and replace and click replace all button. This should solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!