简体   繁体   中英

Delete blank lines in CSV file with PHP or PHPExcel?

I am trying programmatically delete blank lines in CSV files using PHP. Files are uploaded to a site and converted to CSV using PHPExcel. A particular type of CSV is being generated with blank lines in between the data rows, and I'm trying to clean them up with PHP without any luck. Here is an example of what this CSV looks like: https://gist.github.com/vinmassaro/467ea98151e26a79d556

I need to load the CSV, remove the blank lines, and save it, using either PHPExcel or standard PHP functions. Thanks in advance.

EDIT: Here is a snippet from how it is currently converted with PHPExcel. This is part of a Drupal hook, acting on a file that has just been uploaded. I couldn't get the PHPExcel removeRow method working because it didn't seem to work on blank lines, only empty data rows.

// Load the PHPExcel IOFactory.
require_once(drupal_realpath(drupal_get_path('module', 'custom')) . '/PHPExcel/Classes/PHPExcel/IOFactory.php');

// Load the uploaded file into PHPExcel for normalization.
$loaded_file = PHPExcel_IOFactory::load(drupal_realpath($original_file->uri));
$writer = PHPExcel_IOFactory::createWriter($loaded_file, 'CSV');
$writer->setDelimiter(",");
$writer->setEnclosure("");

// Get path to files directory and build a new filename and filepath.
$files_directory = drupal_realpath(variable_get('file_public_path', conf_path() . '/files'));
$new_filename = pathinfo($original_file->filename, PATHINFO_FILENAME) . '.csv';
$temp_filepath = $files_directory . '/' . $new_filename;

// Save the file with PHPExcel to the temp location. It will be deleted later.
$writer->save($temp_filepath);

If you want to use phpexcel, search for CSV.php and edit this File:

// Write rows to file
for ($row = 1; $row <= $maxRow; ++$row) {
    // Convert the row to an array...
    $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row, '', $this->preCalculateFormulas);
    // edit by ger
    //  if last row, then no linebreak will added
    if($row == $maxRow){ $ifMaxRow = TRUE; }else{ $ifMaxRow = False; }
    // ... and write to the file
    $this->writeLine($fileHandle, $cellsArray[0], $ifMaxRow);
}

at the end of file edit this

 /**
 *  Write line to CSV file
 *  
 *  edit by ger
 *  
 *  @param    mixed    $pFileHandle    PHP filehandle
 *  @param    array    $pValues        Array containing values in a row
 *  @throws    PHPExcel_Writer_Exception
 */
private function writeLine($pFileHandle = null, $pValues = null, $ifMaxRow = false)
{
...
            // Add enclosed string
            $line .= $this->enclosure . $element . $this->enclosure;
        }

insert this following     

        if($ifMaxRow == false){
           // Add line ending
           $line .= $this->lineEnding;
        }

Using str_replace as in Mihai Iorga's comment will work. Something like:

$csv = file_get_contents('path/file.csv');
$no_blanks = str_replace("\r\n\r\n", "\r\n", $csv);
file_put_contents('path/file.csv', $no_blanks);

I copied the text from the example you posted, and this worked, although I had to change the "find" parameter to to "\\r\\n \\r\\n" instead of "\\r\\n\\r\\n" because of a single space on each of the blank- looking lines.

Try this:

<?php

$handle = fopen("test.csv", 'r'); //your csv file
$clean = fopen("clean.csv", 'a+'); //new file with no empty rows

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    if($num > 1)
    fputcsv($clean, $data ,";");
}
fclose($handle);
fclose($clean);

?>

Tested on my localhost.

Output Data:

Initial File:

col1,col2,col3,col4,col5,col6,col7,col8

0,229.500,7.4,3165.5,62,20.3922,15.1594,0

1,229.600,8.99608,3156.75,62,15.6863,16.882,0

2,229.700,7.2549,3130.25,62,16.8627,15.9633,0

3,229.800,7.1098,3181,62,17.2549,14.1258,0

Clean Csv File:

col1    col2    col3    col4    col5    col6    col7    col8
0       229.500 7.4     3165.5    62    203.922 151.594 0
1       229.600 899.608 3156.75   62    156.863 16.882  0
2       229.700 72.549  3130.25   62    168.627 159.633 0
3       229.800 71.098  3181      62    172.549 141.258 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM