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

PHP reads CSV file content (example)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 08:55:021147browse
  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 {
  10. if($row === 1)//The first row is used as a field
  11. {
  12. $dataName[] = $dataSrc[$c];//Field name
  13. }
  14. else
  15. { // bbs.it-home.org
  16. foreach ($dataName as $k=>$v)
  17. {
  18. if($k == $c)//Corresponding field
  19. {
  20. $data[$v] = $dataSrc[$c];
  21. }
  22. }
  23. }
  24. }
  25. if(!empty($data))
  26. {
  27. $dataRtn[] = $data;
  28. unset($data);
  29. }
  30. $row++;
  31. }
  32. fclose($handle);
  33. return $dataRtn;
  34. }
  35. }
  36. $aData = getCSVdata('test.csv');
  37. print_r($aData);
  38. ?>
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