php教程 fputcsv() 函數csv資料讀寫資料庫教程檔案代碼
fputcsv() 函數用於將資料格式為csv格式,以便寫入檔案或者資料庫。
1.將字串寫入csv檔案中
$test_array = array(
array("111","sdfsd","sdds","43344","rrrr"),
array("sssssssss","gdfgfd","232323","wwewe","dsfds"),
array("fgfg","e4343","dsfds","w2332","xcvxc"),
array("11212","2323","344343","344343","rerreer"),
array("fds","43344444","33333333","ttttttt","gggggggggggg"),
array("kdfs","dsfdsfds","wewewe","sdsdddddddd","wwwwwwwwwww")
);
$file = fopen("test.csv","w") or die("Can't Open test.csv");
foreach($test_array as $line_array)
{
$isSuccess = fputcsv($file,$line_array);
print $isSuccess."<br>";
if($isSuccess===false)
{
die("Can't write csv line".$line_array);
}
}
fclose($file) or die("Can't close file test.csv.");
fputcsv()函數返回所寫入行的字元的個數或者false,當寫入失敗時返回false。
2.將格式化的csv字串儲存到字串中。
$test_array = array(
array("111","sdfsd","sdds","43344","rrrr"),
array("sssssssss","gdfgfd","232323","wwewe","dsfds"),
array("fgfg","e4343","dsfds","w2332","xcvxc"),
array("11212","2323","344343","344343","rerreer"),
array("fds","43344444","33333333","ttttttt","gggggggggggg"),
array("kdfs","dsfdsfds","wewewe","sdsdddddddd","wwwwwwwwwww")
);
ob_start();
$file = fopen("php://output","w") or die("Can't Open php://output");
foreach($test_array as $line_array)
{
$isSuccess = fputcsv($file,$line_array);
if($isSuccess===false)
{
die("Can't write csv line".$line_array);
}
}
fclose($file) or die("Can't close file test.csv.");
$result = ob_get_contents();
ob_end_clean();
以用fgetcsv(file,length,separator,enclosure)函數讀取csv檔案。
fgetcsv的參數說明如下:
file:需要讀取的csv檔案,此參數是必需的。
length:表示大於csv檔案中最長的行的長度的值。php5之前是必需參數。在php5中是選擇性參數,如果不設定此參數或者將其設為0,php將會讀取
一整行的資料。如果行的長度超過8192個位元組時,應該將length值設定一個數,而不是讓php自動去計算行的長度。
separator:指定資料的分隔字元,預設是逗號,如果指定為“;”,那麼fgetcsv函數將按照“;”來解析行資料。
fgetcsv的傳回值:
根據file的一行資料,返回一個數組。如果讀取檔案出錯,則返回false。到達檔案尾部時,也返回false。
下面是一個讀取test.csv檔案的例子。
$file = fopen('test.csv','r') or die("Can't open file test.csv");
$color="#ff0000";
print '<table border=0>';
while($csv_line=fgetcsv($file))
{
print "<tr>";
$len = count($csv_line);
for($i=0;$i<$len;$i++)
{
if($i%2==0)$color="#cccccc";
else $color="#999999";
print '<td bgcolor='.$color.'>'.htmlentities($csv_line[$i]).'</td>';
}
print "</tr>";
}
print '</table>';
fclose($file) or die("Can't close file test.csv!");