我想將表單資料附加到存盤在服務器上的 CSV 檔案中,資料應作為新行添加。我試過
$list = array(
'Peter,Griffin,Oslo,Norway,Norway,Norway,Norway,Norway',
'Glenn,Quagmire,Oslo,Norway,Norway,Norway,Norway,Norway',
);
print_r($list);
$file = fopen('db.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line){
fputcsv($file,explode(',',$line));
}
fclose($file);
但不能在檔案末尾添加資料。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
fopen(FILENAME, 'a');在呼叫之前,您應該以附加模式打開 CSV 檔案fputcsv():
<?php
define('FILENAME', 'file.csv');
$lines = [
['aaa', 'bbb', 'ccc'],
['123', '456', '789'],
['Quotes " get repeated twice', 'If commas , then it will be surounded by quotes', 'ccc'],
];
// Fill the CSV file.
$file = fopen(FILENAME, 'w');
foreach ($lines as $fields) {
fputcsv($file, $fields);
}
fclose($file);
// Add a new line at the end of the file
$file = fopen(FILENAME, 'a');
fputcsv($file, ['another', 'line', 'at the end']);
fclose($file);
?>
擁有 CSV 檔案的寫入權限非常重要,否則您將無法向其附加資料。檔案的用戶和組可能與 PHP 行程不同。這在很大程度上取決于您的托管服務。最好的辦法是檢查您的 SSH 或 FTP 用戶與運行您的網站的 PHP 是否在同一個組中。如果兩者都在同一個組中,那么您可以只向用戶和組授予寫入權限,而只為其他用戶讀取:
chmod ug=rw,o=r db.csv
甚至沒有其他用戶的讀取權限,這會更好:
chmod ug=rw,o= db.csv
由您決定,看看什么是最好的。您還可以使用或甚至更改檔案的用戶chown username db.csv和chgrp groupname db.csv組chown username:groupname db.csv。
為了處理逗號字符周圍的最終空格,我替換了您的代碼explode(',', $line):preg_split('/\s*,\s*/', $line)
<?php
// Just to see the var_export() in plain text instead of HTML.
header('Content-Type: text/plain;charset=utf-8');
// With spaces or tabs around the commas for the preg_split() demo.
$lines = array(
"Peter,\tGriffin,Oslo, Norway,Norway ,Norway, Norway,Norway",
'Glenn, Quagmire, Oslo, Norway, Norway, Norway, Norway, Norway',
);
var_export($lines);
$file = fopen('db.csv', 'a');
foreach ($lines as $line) {
fputcsv($file, preg_split('/\s*,\s*/', $line));
}
fclose($file);
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/417674.html
標籤:
