Phpcsvtoarray (csv to array) method and code-php Tutorial

Source: Internet
Author: User
Phpcsvtoarray (csv to array) method and code

  1. // Ini_set ('memory _ limit ','-1'); // if the csv value is large, you can add it.
  2. /*
  3. * $ File: csv file
  4. * $ CsvDataArr: header of csv table, eg: arary ('name', 'sex', 'age') or array (0, 1, 2)
  5. * $ Specialhtml: whether do you want to convert special characters to html entities?
  6. * $ Removechar: which type do you 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 = 1000, $ 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 ('&', '"', '\'',' <','> '), 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 (array ('&', '"', '\'',' <','> ',' (',') ',' % '), '', trim ($ value ));
  70. }
  71. Private function remove_char_auto ($ str, $ x = 0)
  72. {
  73. $ X = 0? $ Str = $ this-> make_semiangle ($ str ):'';
  74. Eregi ('[: punct:]', $ str, $ arr );
  75. $ Str = str_replace ($ arr [0], '', $ str );
  76. Return eregi ('[: punct:]', $ 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' => 'D ', 'E' => 'e ',
  83. 'F' => 'F', 'G' => 'G', 'H' => 'h', 'I' => 'I ', 'j' => 'J ',
  84. 'K' => 'K', 'L' => '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' => 'L', 'M' =>'m ', 'n' => 'N ',
  90. 'O' => 'O', 'P' => 'P', 'q' => 'Q', 'R' => 'R ','s '=>'s ',
  91. 'T' => 'T', 'u' => 'u', 'V' => 'V', 'W' => 'W ', 'X' => 'X ',
  92. 'Y' => 'y', 'Z' => 'Z ',
  93. '(' => '(', ')' => ')', '[' => '[', ']' => ']', '[' => '[',
  94. ']' => ']', '<' => '[', '<' => ']', '=> '[', '"' => ']',
  95. ''' => '[', ''' => ']', '{' => '{', '}' => '}', '=>' <',
  96. '"' => ',
  97. '%' => '%', '+' => '+', '-' => '-', '-' => '-','~ '=> '-',
  98. ':' => ':','. '=>'. ',', '=>', '=>'. ',', '=> '.',
  99. ';' => ',','? '=> '? ','! '=> '! ','... '=>'-', ''' =>' | ',
  100. '"' => '"', ''' => ''', ''' => ''', '|' => '| ', 'Region' => '"',
  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. ?>

2. use common 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 (1, 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. ?>

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. ?>

As for which one is better, it depends on your actual needs and hobbies. in actual work, there are still a lot of requirements for converting csv to array. we suggest you practice more and learn more.

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.