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('/^"(.+)"[\r\n]*$/', $p, $match ))
  28. {
  29. $p = $match[1];
  30. }
  31. $a[] = str_replace('""','"',$p);
  32. }while( count($src) > 0 );
  33. return $a;
  34. }
  35.  
  36.  
  37. function file_getcsv( $f )
  38. {
  39. $line = fgets( $f );
  40. while( ($a = str_to_csv($line))===false )
  41. {
  42. if( feof($f) ){ return false; }
  43. $line .= "\n".fgets( $f );
  44. }
  45. return $a;
  46. }
  47.  
  48.  
  49. function file_to_csv( $filename )
  50. {
  51. ini_set("auto_detect_line_endings", true);
  52. $a = array();
  53. $f = fopen($filename,'r');
  54. while( !feof($f) )
  55. {
  56. $rec = file_getcsv($f);
  57. if( $rec===false ){ return false; }
  58. if( !empty($rec) )
  59. {
  60. $a[] = $rec;
  61. }
  62. }
  63. fclose($f);
  64. return $a;
  65. }
  66.  
  67. $data = file_to_csv('sample.csv');
  68.  
  69. echo '<pre>';print_r($data);

Report this snippet  

You need to login to post a comment.