Home  >  Article  >  Backend Development  >  PHP reads CSV file content (example)

PHP reads CSV file content (example)

WBOY
WBOYOriginal
2016-07-25 08:55:021060browse
  1. function getCSVdata($filename)
  2. {
  3. $row = 1;//Start of the first line
  4. if(($handle = fopen($filename, "r")) !== false)
  5. {
  6. while(($dataSrc = fgetcsv($handle)) !== false)
  7. {
  8. $num = count($dataSrc);
  9. for ($c=0; $c < $num; $ c++)//Column
  10. {
  11. if($row === 1)//The first row is used as a field
  12. {
  13. $dataName[] = $dataSrc[$c];//Field name
  14. }
  15. else
  16. { // bbs.it-home.org
  17. foreach ($dataName as $k=>$v)
  18. {
  19. if($k == $c)//Corresponding field
  20. {
  21. $data[$v] = $dataSrc[$c];
  22. }
  23. }
  24. }
  25. }
  26. if(!empty($data))
  27. {
  28. $dataRtn[] = $data;
  29. unset($data);
  30. }
  31. $row++;
  32. }
  33. fclose($handle);
  34. return $dataRtn;
  35. }
  36. }
  37. $aData = getCSVdata('test.csv');
  38. print_r($aData);
  39. ?>
Copy code

Test Results:

Array ( [0] => Array ( [a] => test3 => test4 [c] => ) [1] => Array ( [a] => test5 => [c] => ) )

>>> More about php exporting csv and php reading and writing csv files.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn