PHP csv to Array (CSV-to-array) method and code

Source: Internet
Author: User
  1. Ini_set (' Memory_limit ', '-1 '); If the CSV is larger, you can add them.
  2. /*
  3. * $file: CSV file
  4. * $CSVDATAARR: Header of CSV table, eg:arary (' name ', ' sex ', ' age ') or array (0,1,2)
  5. * $specialhtml: Whether does want to convert special characters to HTML entities?
  6. * $removechar: Which type does want to remove special characters in array keys, manual or Automatical?
  7. * Edit http://bbs.it-home.org
  8. */
  9. Class Csv_to_array
  10. {
  11. Private $counter;
  12. Private $handler;
  13. Private $length;
  14. Private $file;
  15. Private $seprator;
  16. Private $specialhtml;
  17. Private $removechar = ' manual ';
  18. Private $CSVDATAARR;
  19. Private $csvData = Array ();
  20. function __construct ($file = ', $csvDataArr = ', $specialhtml = true, $length = +, $seprator = ', ')
  21. {
  22. $this->counter = 0;
  23. $this->length = $length;
  24. $this->file = $file;
  25. $this->seprator = $seprator;
  26. $this->specialhtml = $specialhtml;
  27. $this->csvdataarr = Is_array ($CSVDATAARR)? $CSVDATAARR: Array ();
  28. $this->handler = fopen ($this->file, "R");
  29. }
  30. function Get_array ()
  31. {
  32. $GETCSVARR = Array ();
  33. $CSVDATAARR = Array ();
  34. while ($data = Fgetcsv ($this->handler, $this->length, $this->seprator))! = FALSE)
  35. {
  36. $num = count ($data);
  37. $GETCSVARR [$this->counter] = $data;
  38. $this->counter++;
  39. }
  40. if (count ($GETCSVARR) > 0)
  41. {
  42. $CSVDATAARR = Array_shift ($GETCSVARR);
  43. if ($this->csvdataarr) $csvDataArr = $this->csvdataarr;
  44. $counter = 0;
  45. foreach ($getCsvArr as $csvValue)
  46. {
  47. $totalRec = count ($csvValue);
  48. for ($i = 0; $i < $totalRec; $i + +)
  49. {
  50. $key = $this->csvdataarr? $CSVDATAARR [$i]: $this->remove_char ($CSVDATAARR [$i]);
  51. if ($csvValue [$i]) $this->csvdata[$counter] [$key] = $this->put_special_char ($csvValue [$i]);
  52. }
  53. $counter + +;
  54. }
  55. }
  56. return $this->csvdata;
  57. }
  58. function Put_special_char ($value)
  59. {
  60. Return $this->specialhtml? Str_replace (' & ', ' ' ', ' ' \ ' ', ' < ', ' > '), Array (' & ', ' "', '" ', ' < ', ' > '), $value): $value;
  61. }
  62. function Remove_char ($value)
  63. {
  64. $result = $this->removechar = = ' manual '? $this->remove_char_manual ($value): $this->remove_char_auto ($value);
  65. Return Str_replace (', ' _ ', trim ($result));
  66. }
  67. Private Function remove_char_manual ($value)
  68. {
  69. Return Str_replace (' & ', ' ' ', ' \ ', ' < ', ' > ', ' (', ') ', '% '), ', Trim ($value));
  70. }
  71. Private Function Remove_char_auto ($str, $x =0)
  72. {
  73. $x ==0? $str = $this->make_semiangle ($str): ";
  74. Eregi (' [[:p UNCT:] ', $STR, $arr);
  75. $str = Str_replace ($arr [0], ", $STR);
  76. return eregi (' [[:p UNCT:]] ', $str)? $this->remove_char_auto ($STR, 1): $STR;
  77. }
  78. Private Function Make_semiangle ($STR)
  79. {
  80. $arr = Array (' 0 ' = ' 0 ', ' 1 ' = ' 1 ', ' 2 ' = ' 2 ', ' 3 ' = ' 3 ', ' 4 ' = ' 4 ',
  81. ' 5 ' = ' 5 ', ' 6 ' = ' 6 ', ' 7 ' = ' 7 ', ' 8 ' = ' 8 ', ' 9 ' = ' 9 ',
  82. ' A ' = ' a ', ' B ' = ' B ', ' c ' = ' C ', ' d ' and '-d ', ' e ' = ' e ',
  83. ' F ' = ' f ', ' g ' = ' g ', ' h ' = = ' h ', ' i ' = ' I ', ' j ' = ' j ',
  84. ' k ' = ' k ', ' l ' = ' + ', ' m ' = = ' m ', ' n ' = ' n ', ' o ' = ' ' O ',
  85. ' P ' = ' P ', ' q ' + = ' q ', ' r ' = = ' R ', ' s ' = + ' s ', ' t ' = ' t ',
  86. ' U ' = ' ' u ', ' v ' = ' = ' V ', ' w ' = = ' W ', ' x ' = ' x ', ' y ' = ' y ',
  87. ' Z ' + ' z ', ' a ' = ' = ' A ', ' B ' = ' B ', ' c ' = ' C ', ' d ' = = ' d ',
  88. ' E ' = ' e ', ' f ' = ' f ', ' g ' = ' = ' g ', ' h ' = ' h ', ' i ' = = ' I ',
  89. ' J ' = ' j ', ' k ' = ' k ', ' l ' = ' = ', ' and ' = ', ' m ' + ' m ', ' n ' = ' n ',
  90. ' O ' = ' ' o ', ' p ' = ' P ', ' q ' = ' Q ', ' r ' = = ' R ', ' s ' = ' and ' s ',
  91. ' t ' = ' t ', ' u ' = ' = ' u ', ' v ' = ' = ' V ', ' w ' = ' W ', ' x ' = ' x ',
  92. ' Y ' = ' y ', ' z ' = ' z ',
  93. ' (' = ' = ' (') ' + ') ', ' (' = ' = ' [', ') ' + '] ', ' ' ' + ', ' [',
  94. ' ' ' = ' and ' ', ' ' = ' = ' [', ' ' ' ' = '] ', ' ' ' ' ' = ' [', ' ' '
  95. ' = ' + ' [', ' ' + '] ', ' {' = ' = ', '} ' = '} ', ' ' = ' < ',
  96. ' ' = ' > ',
  97. '% ' = '% ', ' + ' = ' + ', '-' = '-', '-' = '-', ' ~ ' = '-',
  98. ': ' = ': ', '. ' = = ', ', ', ' = = ', ', ', ' = ', ', ', ' = ', '
  99. '; ' = ', ', '? ' = = '? ', '! ' + '! ', ' ... ' + '-', ' ‖ ' = ' | ',
  100. ' ' ' = ' ', ' ' ' and ' ', ' ' and ' ', ' ' and ' ', ' | '
  101. ' = ' + ', ' $ ' + ' $ ', ' @ ' + ' @ ', ' # ' + ' # ', ' ^ ' + ' ^ ', ' & ' + ' & ', ' * ' = ' * ';
  102. Return Strtr ($str, $arr);
  103. }
  104. function __destruct () {
  105. Fclose ($this->handler);
  106. }
  107. }
  108. Example
  109. $csv = new Csv_to_array (' user.csv ');
  110. echo "
    "; Print_r ($csv->get_array ()); echo "
    ";
  111. ?>
Copy Code

2. Use General functions

  1. function Csv_to_array ($csv)
  2. {
  3. $len = strlen ($csv);
  4. $table = Array ();
  5. $cur _row = Array ();
  6. $cur _val = "";
  7. $state = "First item";
  8. for ($i = 0; $i < $len; $i + +)
  9. {
  10. Sleep (1000);
  11. $ch = substr ($csv, $i, 1);
  12. if ($state = = "First item")
  13. {
  14. if ($ch = = ' "') $state =" we ' re quoted Hea ";
  15. ElseIf ($ch = = ",")//empty
  16. {
  17. $cur _row[] = ""; Done with first one
  18. $cur _val = "";
  19. $state = "First item";
  20. }
  21. ElseIf ($ch = = "\ n")
  22. {
  23. $cur _row[] = $cur _val;
  24. $table [] = $cur _row;
  25. $cur _row = Array ();
  26. $cur _val = "";
  27. $state = "First item";
  28. }
  29. ElseIf ($ch = = "\ r") $state = "Wait for a line feed, if so close out row!";
  30. Else
  31. {
  32. $cur _val. = $ch;
  33. $state = "Gather not quote";
  34. }
  35. }
  36. ElseIf ($state = = "we ' re quoted Hea")
  37. {
  38. if ($ch = = ' ") $state =" Potential End Quote found ";
  39. else $cur _val. = $ch;
  40. }
  41. ElseIf ($state = = "potential End Quote found")
  42. {
  43. if ($ch = = ' "')
  44. {
  45. $cur _val. = ' "';
  46. $state = "we ' re quoted Hea";
  47. }
  48. ElseIf ($ch = = ', ')
  49. {
  50. $cur _row[] = $cur _val;
  51. $cur _val = "";
  52. $state = "First item";
  53. }
  54. ElseIf ($ch = = "\ n")
  55. {
  56. $cur _row[] = $cur _val;
  57. $table [] = $cur _row;
  58. $cur _row = Array ();
  59. $cur _val = "";
  60. $state = "First item";
  61. }
  62. ElseIf ($ch = = "\ r") $state = "Wait for a line feed, if so close out row!";
  63. Else
  64. {
  65. $cur _val. = $ch;
  66. $state = "we ' re quoted Hea";
  67. }
  68. }
  69. ElseIf ($state = = "Wait for a line feed, if so close out row!")
  70. {
  71. if ($ch = = "\ n")
  72. {
  73. $cur _row[] = $cur _val;
  74. $cur _val = "";
  75. $table [] = $cur _row;
  76. $cur _row = Array ();
  77. $state = "First item";
  78. }
  79. Else
  80. {
  81. $cur _row[] = $cur _val;
  82. $table [] = $cur _row;
  83. $cur _row = Array ();
  84. $cur _val = $ch;
  85. $state = "Gather not quote";
  86. }
  87. }
  88. ElseIf ($state = = "Gather not quote")
  89. {
  90. if ($ch = = ",")
  91. {
  92. $cur _row[] = $cur _val;
  93. $cur _val = "";
  94. $state = "First item";
  95. }
  96. ElseIf ($ch = = "\ n")
  97. {
  98. $cur _row[] = $cur _val;
  99. $table [] = $cur _row;
  100. $cur _row = Array ();
  101. $cur _val = "";
  102. $state = "First item";
  103. }
  104. ElseIf ($ch = = "\ r") $state = "Wait for a line feed, if so close out row!";
  105. else $cur _val. = $ch;
  106. }
  107. }
  108. return $table;
  109. }
  110. Pass a CSV string, get a PHP array
  111. Example
  112. $arr = Csv_to_array (file_get_contents (' user.csv '));
  113. echo "
    "; Print_r ($arr);   echo "
    "
  114. ?>
Copy Code

Or

    1. $arrCSV = Array ();
    2. Open the CSV
    3. if ($handle = fopen ("User.csv", "R"))!==false) {
    4. Set the parent array key to 0
    5. $key = 0;
    6. While there is data available loop through unlimited times (0) using separator (,)
    7. while ($data = fgetcsv ($handle, 0, ","))!==false) {
    8. Count the total keys in each row
    9. $c = count ($data);
    10. Populate the array
    11. for ($x =0; $x < $c; $x + +) $arrCSV [$key] [$x] = $data [$x];
    12. $key + +;
    13. }//End While
    14. Close the CSV file
    15. Fclose ($handle);
    16. }//End If
    17. echo "
      "; Print_r ($arrCSV); echo "
      ";
    18. ?>
Copy Code

As to which kind of better use, see their actual needs and personal hobbies, the actual work of the CSV to the array of demand is still a lot, suggest that we practice more, more master.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.