dongtuji0992 2013-10-21 14:19
浏览 278


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:

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');

// 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.
  • 写回答

3条回答 默认 最新

  • dream1849 2013-10-21 15:08

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

    $csv = file_get_contents('path/file.csv');
    $no_blanks = str_replace("
    ", "
    ", $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 " " instead of " " because of a single space on each of the blank-looking lines.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!