[英]Remove Blank ROWS from CSV files in php
Is it possible to remove all blank ROWS from a CSV file? 是否可以从CSV文件中删除所有空白的ROWS?
I'm trying to count all rows from a CSV file but would like to exclude lines that doesn't contain a value on a specific column or the whole row. 我正在尝试计算CSV文件中的所有行,但想排除不包含特定列或整个行中的值的行。
This is what I'm using to count the rows as of the moment. 这就是我目前用来计算行数的内容。
$import = file($target_path, FILE_SKIP_EMPTY_LINES);
$num_rows = count($import);
echo $num_rows;
sample: 样品:
Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,Nell@Gmail.Com,1990,CHEVROLET,K1500,,
,,,,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,
Nella,Brown,111 Venna St,Princeton,TX,75407,2147177671,lakb@Gmail.Com,1993,CHEVROLET,K1500,,
Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,Nell@Gmail.Com,1990,CHEVROLET,K1500,,
,,,,,,,,,,,,
Jun,Bronse,137 Raven,Princeton,TX,75407,2147088671,Nell@Gmail.Com,1990,CHEVROLET,K1500,,
$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: 基本上是Barmar已经发布的内容,但是如果您需要处理(许多)大文件,我建议您尝试
rtrim
(或ltrim
),因为通常对于像您这样的任务来说,它们会更快一些:
$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. 使用记事本++打开.csv文件。 Then search for
^\\*s
goto find and replace and click replace all button. 然后搜索
^\\*s
转到查找和替换,然后单击全部替换按钮。 This should solve your problem. 这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.