PHP操作csv文件
fputcsv() 函数将行格式化为 CSV 并写入一个打开的文件。
fgetcsv() 函数从文件指针中读入一行并解析 CSV 字段。
fputcsv案例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?php date_default_timezone_set('PRC'); header("Content-type:text/html;charset=utf-8"); $fileName='D:/myenv/Apache2.2/htdocs/test/csv/'.date('Y-m-dHi',time()).'.csv'; //$fileName=str_replace("\\","/",$fileName); $content=array(); for ($i=1;$i<13;$i++){ $content[]='内容'.$i; } //判断文件是否存在 if(!file_exists($fileName)){ $fp=fopen($fileName,'a+'); $test_array = array( array("companyId1","companyId2","companyId3","companyId4","companyId5","companyId6","companyId7","companyId8","companyId9","companyId10","companyId11","companyId12") ); foreach($test_array as $line_array) { $isSuccess = fputcsv($fp,$line_array); if($isSuccess===false) { die("Can't write csv line".$line_array); } } $test_array2[] = $content; foreach ($test_array2 as $k=>$line_array) { $isSuccess = fputcsv($fp, $line_array); if ($isSuccess === false) { die("Can't write csv line" . $line_array); } } }else { $fp=fopen($fileName,'a+'); $test_array[] = $content; foreach ($test_array as $k=>$line_array) { $isSuccess = fputcsv($fp, $line_array); //print $isSuccess . "<br>"; if ($isSuccess === false) { die("Can't write csv line" . $line_array); } } $test_array=array(); } fclose($fp); exit; |
结果:
fgetcsv案例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php date_default_timezone_set('PRC'); header("Content-type:text/html;charset=utf-8"); $fileName='D:/myenv/Apache2.2/htdocs/test/csv/2016-08-091613.csv'; $fileName=str_replace("\\","/",$fileName); $file = fopen($fileName,'r'); $content=array(); while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容 $content[] = $data; } var_dump($content);exit; |
结果:
1 |
array(2) { [0]=> array(12) { [0]=> string(10) "companyId1" [1]=> string(10) "companyId2" [2]=> string(10) "companyId3" [3]=> string(10) "companyId4" [4]=> string(10) "companyId5" [5]=> string(10) "companyId6" [6]=> string(10) "companyId7" [7]=> string(10) "companyId8" [8]=> string(10) "companyId9" [9]=> string(11) "companyId10" [10]=> string(11) "companyId11" [11]=> string(11) "companyId12" } [1]=> array(12) { [0]=> string(7) "内容1" [1]=> string(7) "内容2" [2]=> string(7) "内容3" [3]=> string(7) "内容4" [4]=> string(7) "内容5" [5]=> string(7) "内容6" [6]=> string(7) "内容7" [7]=> string(7) "内容8" [8]=> string(7) "内容9" [9]=> string(8) "内容10" [10]=> string(8) "内容11" [11]=> string(8) "内容12" } } |
- PHP中利用cookie实现自动登录(案例)
- PHP读取二进制文件头判断文件类型