search
HomeBackend DevelopmentPHP Tutorialphp csv to array (csv to array) method and code

  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 {
  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 "
    ";
  109. ?>
复制代码

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 {
  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 "
    "
  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 "
    ";
  17. ?>
复制代码

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



Statement
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version