二话不说 直接上代码

  1. function getCSVdata($filename)
  2. {
  3. 	$row = 1;//第一行开始
  4. 	if(($handle = fopen($filename, "r")) !== false){
  5. 	    while(($dataSrc = fgetcsv($handle)) !== false){
  6. 	        $num = count($dataSrc);
  7. 	        for ($c=0; $c < $num; $c++){//列 column
  8.                  if($row === 1){//第一行作为字段
  9.                         $dataName[] = $dataSrc[$c];//字段名称
  10.  	        }else{
  11. 	        	foreach($dataName as $k=-->$v){
  12. 	        	    if($k == $c){//对应的字段
  13. 	            	        $data[$v] = $dataSrc[$c];
  14. 	        	     }
  15. 	        	}
  16. 	            }
  17. 	        }
  18. 	        if(!empty($data)){
  19. 		         $dataRtn[] = $data;
  20. 		         unset($data);
  21. 	        }
  22. 	        $row++;
  23. 	    }
  24. 	    fclose($handle);
  25. 	    return $dataRtn;
  26. 	}
  27. }
  28.  
  29. $aData = getCSVdata('test.csv');
  30. var_dump($aData);

CSV文件内容:

得到的结果是:

array
0 =>
array
‘detail’ => string ‘a1’ (length=2)
‘nickname’ => string ‘b1’ (length=2)
‘title’ => string ‘c1’ (length=2)
1 =>
array
‘detail’ => string ‘a2’ (length=2)
‘nickname’ => string ‘b2’ (length=2)
‘title’ => string ‘c2’ (length=2)
2 =>
array
‘detail’ => string ‘a3’ (length=2)
‘nickname’ => string ‘b3’ (length=2)
‘title’ => string ‘c3’ (length=2)

4 thoughts on “PHP读取CSV文件”

  1. Hello there I am so thrilled I found your website, I really found you
    by accident, while I was researching on Digg for something else,
    Nonetheless I am here now and would just like to say thank you for a incredible post and a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at
    the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read more, Please do keep up the superb work.

发表评论

电子邮件地址不会被公开。 必填项已用*标注