{"id":129430,"date":"2022-11-02T14:28:34","date_gmt":"2022-11-02T14:28:34","guid":{"rendered":"https:\/\/phppot.com\/?p=19961"},"modified":"2022-11-02T14:28:34","modified_gmt":"2022-11-02T14:28:34","slug":"how-to-read-a-csv-to-array-in-php","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/11\/02\/how-to-read-a-csv-to-array-in-php\/","title":{"rendered":"How to Read a CSV to Array in PHP"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1304347826087\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on November 2nd, 2022.<\/div>\n<p>There are many ways to read a CSV file to an array. Online hosted tools provide interfaces to do this. Also, it is very easy to create a custom user interface for the purpose of reading CSV to the array.<\/p>\n<p>In PHP, it has more than one native function to read CSV data.<\/p>\n<ul>\n<li>fgetcsv() \u2013 It reads the CSV file pointer and reads the line in particular to the file handle.<\/li>\n<li>str_getcsv() -It reads the input CSV string into an array.<\/li>\n<\/ul>\n<p>This article provides alternate ways of reading a CSV file to a PHP array. Also, it shows how to prepare HTML from the array data of the input CSV.<\/p>\n<h2>Quick example<\/h2>\n<p>This example reads an input CSV file using the PHP fgetcsv() function. This function needs the file point to refer to the line to read the CSV row columns.<\/p>\n<div class=\"post-section-highlight\" readability=\"39\">\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php \/\/ PHP function to read CSV to array\nfunction csvToArray($csv)\n{ \/\/ create file handle to read CSV file $csvToRead = fopen($csv, 'r'); \/\/ read CSV file using comma as delimiter while (! feof($csvToRead)) { $csvArray[] = fgetcsv($csvToRead, 1000, ','); } fclose($csvToRead); return $csvArray;\n} \/\/ CSV file to read into an Array\n$csvFile = 'csv-to-read.csv';\n$csvArray = csvToArray($csvFile); echo '&lt;pre&gt;';\nprint_r($csvArray);\necho '&lt;\/pre&gt;';\n?&gt;\n<\/code><\/pre>\n<\/div>\n<p>This program sets the CSV file stream reference and other parameters to read the records in a loop.<\/p>\n<p>The loop iteration pushes the line data into an array. The <a href=\"https:\/\/phppot.com\/php\/php-array-push\/\">PHP array push<\/a> happens using one of the methods we have seen in the linked article.<\/p>\n<p>Save the below comma-separated values to a csv-to-array.csv file. It has to be created as an input of the above program.<\/p>\n<p class=\"code-heading\">csv-to-array.csv<\/p>\n<pre class=\"prettyprint\"><code>Lion,7,Wild\nTiger,9,Wild\nDog,4,Domestic\n<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>The above program returns the following array after <a href=\"https:\/\/phppot.com\/php\/import-csv-file-into-mysql-using-php\/\">reading the input CSV file<\/a> data.<\/p>\n<pre class=\"prettyprint\"><code>Array\n( [0] =&gt; Array ( [0] =&gt; Lion [1] =&gt; 7 [2] =&gt; Wild ) [1] =&gt; Array ( [0] =&gt; Tiger [1] =&gt; 9 [2] =&gt; Wild ) [2] =&gt; Array ( [0] =&gt; Dog [1] =&gt; 4 [2] =&gt; Domestic ) )\n<\/code><\/pre>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19981\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-php-array-550x389.jpg\" alt=\"csv to PHP array\" width=\"550\" height=\"389\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-php-array-550x389.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-php-array-300x212.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-php-array-768x543.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-php-array.jpg 1000w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>Map str_getcsv() to read CSV and convert it into a PHP array<\/h2>\n<p>This program will be suitable if you want to skip the step of writing a loop. It saves the developer\u2019s effort. But the background processing will be the same as the above program.<\/p>\n<p>The PHP file() converts the entire CSV into an array. Then, the array_map sets the str_getcsv() function as a callback to iterate the array of CSV file rows.<\/p>\n<p>The str_getcsv() imports the CSV row data into an array. In a previous article, we have seen about <a href=\"https:\/\/phppot.com\/php\/how-to-handle-csv-with-php-read-write-import-export-with-database\/\">handling CSV file read and other operations like import, and export<\/a>.<\/p>\n<p>The resultant $csvArray variable will contain the complete CSV data in a multi-dimensional array.<\/p>\n<p>The output of this program will be similar to that of the quick example.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\n\/\/ a one-line simple option to reade CSV to array\n\/\/ it uses PHP str_getcsv\n$csvArray = array_map('str_getcsv', file('csv-to-read.csv'));\necho '&lt;pre&gt;';\nprint_r($csvArray);\necho '&lt;\/pre&gt;';\n?&gt;\n<\/code><\/pre>\n<h2>Convert CSV to Array and then convert array to HTML<\/h2>\n<p>This example will be useful if you want to display the CSV content in the UI in a tabular form.<\/p>\n<p>Mostly, this code must be more useful since it has the possibility of using it in real-time projects. But, the other examples are basics which are also important to learn about reading CSV using PHP.<\/p>\n<p>This code iterates the CSV row and reads the column data using fgetcsv() as did in the quick example.<\/p>\n<p>Then, it forms the HTML table structure using the CSV array data. In a previous tutorial, we saw code to <a href=\"https:\/\/phppot.com\/javascript\/convert-html-table-excel-javascript\/\">convert an HTML table into an excel<\/a>.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php \/\/ PHP script to read CSV and convert to HTML table \/\/ create file handle to read CSV file\n$csvFile = fopen('csv-to-read.csv', 'r'); if ($csvFile !== FALSE) { echo \"&lt;table border=1 cellpadding=10&gt;\"; while (($csvArray = fgetcsv($csvFile, 100, ',')) !== FALSE) { echo \"&lt;tr&gt;\"; for ($i = 0; $i &lt; count($csvArray); $i ++) { echo \"&lt;td&gt;\" . $csvArray[$i] . \"&lt;\/td&gt;\"; } echo \"&lt;\/tr&gt;\"; } echo \"&lt;\/table&gt;\"; fclose($csvFile);\n}\n?&gt;\n<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>This program will display the HTML table on the screen. The row data is from the input CSV file.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-19979\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/10\/csv-to-html.jpg\" alt=\"csv to html\" width=\"300\" height=\"215\"><br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/csv-to-array.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-csv-to-array\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on November 2nd, 2022. There are many ways to read a CSV file to an array. Online hosted tools provide interfaces to do this. Also, it is very easy to create a custom user interface for the purpose of reading CSV to the array. In PHP, it has more than one [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":129431,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-129430","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=129430"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129430\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/129431"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=129430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=129430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=129430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}