Posted By

hgc81538 on 08/28/12


Tagged

csv


Versions (?)

CSV(unicode) file to php array


 / Published in: PHP
 

CSV(unicode) file to php array

  1. sample.csv
  2. ----------------
  3. name,email
  4. 政府,[email protected]
  5. 한국,[email protected]
  6. ----------------
  7.  
  8. =======================================
  9. <?php
  10.  
  11. function str_to_csv( $row )
  12. {
  13. if( $row=='' )
  14. {
  15. return array();
  16. }
  17. $a = array();
  18. $src = explode(',', $row );
  19. do{
  20. $p = array_shift($src);
  21. while( mb_substr_count($p,'"') % 2 != 0 )
  22. {
  23. if( count($src)==0 ){ return false; }
  24. $p .= ','.array_shift($src);
  25. }
  26. $match = null;
  27. if( preg_match('/^"(.+)"[
  28. ]*$/', $p, $match ))
  29. {
  30. $p = $match[1];
  31. }
  32. $a[] = str_replace('""','"',$p);
  33. }while( count($src) > 0 );
  34. return $a;
  35. }
  36.  
  37.  
  38. function file_getcsv( $f )
  39. {
  40. $line = fgets( $f );
  41. while( ($a = str_to_csv($line))===false )
  42. {
  43. if( feof($f) ){ return false; }
  44. $line .= "\n".fgets( $f );
  45. }
  46. return $a;
  47. }
  48.  
  49.  
  50. function file_to_csv( $filename )
  51. {
  52. ini_set("auto_detect_line_endings", true);
  53. $a = array();
  54. $f = fopen($filename,'r');
  55. while( !feof($f) )
  56. {
  57. $rec = file_getcsv($f);
  58. if( $rec===false ){ return false; }
  59. if( !empty($rec) )
  60. {
  61. $a[] = $rec;
  62. }
  63. }
  64. fclose($f);
  65. return $a;
  66. }
  67.  
  68. $data = file_to_csv('sample.csv');
  69.  
  70. echo '<pre>';print_r($data);

Report this snippet  

You need to login to post a comment.