Heim > Backend-Entwicklung > PHP-Tutorial > php csv to array(csv 转数组)方法与代码

php csv to array(csv 转数组)方法与代码

WBOY
Freigeben: 2016-07-25 08:59:39
Original
1580 Leute haben es durchsucht
  1. //ini_set('memory_limit', '-1'); // 如果csv比较大的话,可以添加。
  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 {
  49. $key = $this->csvDataArr ? $csvDataArr[$i] : $this->remove_char($csvDataArr[$i]);
  50. if($csvValue[$i]) $this->csvData[$counter][$key] = $this->put_special_char($csvValue[$i]);
  51. }
  52. $counter++;
  53. }
  54. }
  55. return $this->csvData;
  56. }
  57. function put_special_char($value)
  58. {
  59. return $this->specialhtml ? str_replace(array('&','" ','\'',''),array('&','"',''','<','>'),$value) : $value;
  60. }
  61. function remove_char($value)
  62. {
  63. $result = $this->removechar == 'manual' ? $this->remove_char_manual($value) : $this->remove_char_auto($value);
  64. return str_replace(' ','_',trim($result));
  65. }
  66. private function remove_char_manual($value)
  67. {
  68. return str_replace(array('&','"','\'','','(',')','%'),'',trim($value));
  69. }
  70. private function remove_char_auto($str,$x=0)
  71. {
  72. $x==0 ? $str=$this->make_semiangle($str) : '' ;
  73. eregi('[[:punct:]]',$str,$arr);
  74. $str = str_replace($arr[0],'',$str);
  75. return eregi('[[:punct:]]',$str) ? $this->remove_char_auto($str,1) : $str;
  76. }
  77. private function make_semiangle($str)
  78. {
  79. $arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
  80. '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
  81. 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
  82. 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
  83. 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
  84. 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
  85. 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
  86. 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
  87. 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
  88. 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
  89. 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
  90. 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
  91. 'y' => 'y', 'z' => 'z',
  92. '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
  93. '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
  94. '‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => ' '》' => '>',
  95. '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
  96. ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
  97. ';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
  98. '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
  99. ' ' => ' ','$'=>'$','@'=>'@','#'=>'#','^'=>'^','&'=>'&','*'=>'*');
  100. return strtr($str, $arr);
  101. }
  102. function __destruct(){
  103. fclose($this->handler);
  104. }
  105. }
  106. // example:
  107. $csv = new csv_to_array('user.csv');
  108. echo "
    "; print_r($csv->get_array()); echo "
    Nach dem Login kopieren
    ";
  109. ?>
复制代码

2、使用一般函数

  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 {
  9. //sleep(1000);
  10. $ch = substr($csv,$i,1);
  11. if ($state == "first item")
  12. {
  13. if ($ch == '"') $state = "we're quoted hea";
  14. elseif ($ch == ",") //empty
  15. {
  16. $cur_row[] = ""; //done with first one
  17. $cur_val = "";
  18. $state = "first item";
  19. }
  20. elseif ($ch == "\n")
  21. {
  22. $cur_row[] = $cur_val;
  23. $table[] = $cur_row;
  24. $cur_row = array();
  25. $cur_val = "";
  26. $state = "first item";
  27. }
  28. elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
  29. else
  30. {
  31. $cur_val .= $ch;
  32. $state = "gather not quote";
  33. }
  34. }
  35. elseif ($state == "we're quoted hea")
  36. {
  37. if ($ch == '"') $state = "potential end quote found";
  38. else $cur_val .= $ch;
  39. }
  40. elseif ($state == "potential end quote found")
  41. {
  42. if ($ch == '"')
  43. {
  44. $cur_val .= '"';
  45. $state = "we're quoted hea";
  46. }
  47. elseif ($ch == ',')
  48. {
  49. $cur_row[] = $cur_val;
  50. $cur_val = "";
  51. $state = "first item";
  52. }
  53. elseif ($ch == "\n")
  54. {
  55. $cur_row[] = $cur_val;
  56. $table[] = $cur_row;
  57. $cur_row = array();
  58. $cur_val = "";
  59. $state = "first item";
  60. }
  61. elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
  62. else
  63. {
  64. $cur_val .= $ch;
  65. $state = "we're quoted hea";
  66. }
  67. }
  68. elseif ($state == "wait for a line feed, if so close out row!")
  69. {
  70. if ($ch == "\n")
  71. {
  72. $cur_row[] = $cur_val;
  73. $cur_val = "";
  74. $table[] = $cur_row;
  75. $cur_row = array();
  76. $state = "first item";
  77. }
  78. else
  79. {
  80. $cur_row[] = $cur_val;
  81. $table[] = $cur_row;
  82. $cur_row = array();
  83. $cur_val = $ch;
  84. $state = "gather not quote";
  85. }
  86. }
  87. elseif ($state == "gather not quote")
  88. {
  89. if ($ch == ",")
  90. {
  91. $cur_row[] = $cur_val;
  92. $cur_val = "";
  93. $state = "first item";
  94. }
  95. elseif ($ch == "\n")
  96. {
  97. $cur_row[] = $cur_val;
  98. $table[] = $cur_row;
  99. $cur_row = array();
  100. $cur_val = "";
  101. $state = "first item";
  102. }
  103. elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
  104. else $cur_val .= $ch;
  105. }
  106. }
  107. return $table;
  108. }
  109. //pass a csv string, get a php array
  110. // example:
  111. $arr = csv_to_array(file_get_contents('user.csv'));
  112. echo "
    "; print_r($arr);   echo "
    Nach dem Login kopieren
    "
  113. ?>
复制代码

或者

  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 $key++;
  12. } // end while
  13. // Close the CSV file
  14. fclose($handle);
  15. } // end if
  16. echo "
    "; print_r($arrCSV); echo "
    Nach dem Login kopieren
    ";
  17. ?>
复制代码

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



Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage