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

Jul 25, 2016 am 08:59 AM

  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的需求还是不少,建议大家多练习,多掌握。



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles