您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關php中的csv文件怎么利用fputcsv()函數進行讀取,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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!");
上述就是小編為大家分享的php中的csv文件怎么利用fputcsv()函數進行讀取了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。