亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 PHP 中刪除 CSV 文件中的空行?

如何在 PHP 中刪除 CSV 文件中的空行?

PHP
www說 2023-08-19 16:15:53
我的 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以便將新行保留在數組中。


查看完整回答
反對 回復 2023-08-19
  • 1 回答
  • 0 關注
  • 146 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號