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!");