我的 output.csv 文件有問題。這就是目前的樣子。我可以創建一個經過修改的新 csv 文件,或者只是修改此 csv 文件,但不知道如何進行。cn,mail,telephonenumber,uid,,,admin,,,"Isaac Newton",[email protected],,newton"Albert Einstein",[email protected],314-159-2653,einstein"Nikola Tesla",[email protected],,tesla我希望輸出是cn,mail,telephonenumber,uidadmin,,,"Isaac Newton",[email protected],,newton"Albert Einstein",[email protected],314-159-2653,einstein"Nikola Tesla",[email protected],,tesla如您所見,第二行已完全刪除。我已經嘗試了以下方法,但它不起作用$lines = file("output.csv", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);$num_rows = count($lines);foreach ($lines as $line) {? ? $csv = str_getcsv($line);? ? if (count(array_filter($csv)) == 0) {? ? ? ? $num_rows--;? ? }}編輯:這是我當前的 PHP? ? ? ? ? ? $filename = "output.csv";? ? ? ? ? ? header('Content-Type: text/csv');? ? ? ? ? ? header('Content-Disposition: attachment; filename="' . $filename . '"');? ? ? ? ? ? $file = fopen("ad.csv","r");? ? ? ? ? ? while(! feof($file))? ? ? ? ? ? ? {? ? ? ? ? ? ? print_r(fgets($file));? ? ? ? ? ? ? }? ? ? ? ? ? fclose($file);所以本質上,我有一個名為“ad.csv”的 csv 文件,其中包含我需要放入“output.csv”中的信息。我想知道如何編輯output.csv,以便在編輯刪除空行后發送下載?目前,Nigel 的代碼附加在底部,它不會編輯輸出的 csv 文件。
1 回答

守著星空守著你
TA貢獻1799條經驗 獲得超8個贊
如果您識別出空行,則可以從原始數組中的行中刪除該行。然后將所有剩余的行放回到同一個文件中......
$lines = file("output.csv", FILE_SKIP_EMPTY_LINES );
$num_rows = count($lines);
foreach ($lines as $lineNo => $line) {
$csv = str_getcsv($line);
if (count(array_filter($csv)) == 0) {
unset($lines[$lineNo]);
}
}
file_put_contents("output.csv", $lines);
我已將其刪除,FILE_IGNORE_NEW_LINES以便將新行保留在數組中。
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消