Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Read a CSV to Array in PHP

#1
How to Read a CSV to Array in PHP

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/11/how-to-read-a-csv-to-array-in-php.jpg" width="550" height="389" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on November 2nd, 2022.</div>
<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>
<p>In PHP, it has more than one native function to read CSV data.</p>
<ul>
<li>fgetcsv() – It reads the CSV file pointer and reads the line in particular to the file handle.</li>
<li>str_getcsv() -It reads the input CSV string into an array.</li>
</ul>
<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>
<h2>Quick example</h2>
<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>
<div class="post-section-highlight" readability="39">
<pre class="prettyprint"><code class="language-php">&lt;?php // PHP function to read CSV to array
function csvToArray($csv)
{ // 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;
} // CSV file to read into an Array
$csvFile = 'csv-to-read.csv';
$csvArray = csvToArray($csvFile); echo '&lt;pre&gt;';
print_r($csvArray);
echo '&lt;/pre&gt;';
?&gt;
</code></pre>
</div>
<p>This program sets the CSV file stream reference and other parameters to read the records in a loop.</p>
<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>
<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>
<p class="code-heading">csv-to-array.csv</p>
<pre class="prettyprint"><code>Lion,7,Wild
Tiger,9,Wild
Dog,4,Domestic
</code></pre>
<p><strong>Output:</strong></p>
<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>
<pre class="prettyprint"><code>Array
( [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 ) )
</code></pre>
<p><img 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/20...00x212.jpg 300w, https://phppot.com/wp-content/uploads/20...68x543.jpg 768w, https://phppot.com/wp-content/uploads/20...-array.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>Map str_getcsv() to read CSV and convert it into a PHP array</h2>
<p>This program will be suitable if you want to skip the step of writing a loop. It saves the developer’s effort. But the background processing will be the same as the above program.</p>
<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>
<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>
<p>The resultant $csvArray variable will contain the complete CSV data in a multi-dimensional array.</p>
<p>The output of this program will be similar to that of the quick example.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
// a one-line simple option to reade CSV to array
// it uses PHP str_getcsv
$csvArray = array_map('str_getcsv', file('csv-to-read.csv'));
echo '&lt;pre&gt;';
print_r($csvArray);
echo '&lt;/pre&gt;';
?&gt;
</code></pre>
<h2>Convert CSV to Array and then convert array to HTML</h2>
<p>This example will be useful if you want to display the CSV content in the UI in a tabular form.</p>
<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>
<p>This code iterates the CSV row and reads the column data using fgetcsv() as did in the quick example.</p>
<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>
<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
$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);
}
?&gt;
</code></pre>
<p><strong>Output:</strong></p>
<p>This program will display the HTML table on the screen. The row data is from the input CSV file.</p>
<p><img 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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-csv-to-array/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/11/...ay-in-php/
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016