Home > Backend Development > PHP Tutorial > php csv to array (csv to array) method and code

php csv to array (csv to array) method and code

WBOY
Release: 2016-07-25 08:59:39
Original
1576 people have browsed it
  1. //ini_set('memory_limit', '-1'); // If the csv is relatively 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. '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
  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 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. ?>
复制代码

或者

  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. ?>
复制代码

至于哪种更好用,看自己的实际需求与个人爱好了,实际工作中csv转array的需求还是不少,建议大家多练习,多掌握。



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template