Converting CSV file into an Array in PHP
Posted By : Ishaan Madan | 12-Jan-2017
This Blog helps to illustrate the method to import CSV file into an associative PHP array. PHP uses
The PHP
Note: Imported CSV must possess first row as column headings as it is used to generate the associative array elements.
Read CSV using PHP
<?php
function ImportCSV2Array($filename)
{
$row = 0;
$col = 0;
$handle = @fopen($filename, "r");
if ($handle)
{
while (($row = fgetcsv($handle, 4096)) !== false)
{
if (empty($fields))
{
$fields = $row;
continue;
}
foreach ($row as $k=>$value)
{
$results[$col][$fields[$k]] = $value;
}
$col++;
unset($row);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() failn";
}
fclose($handle);
}
return $results;
}
Example
<?php
$filename = "demo.csv";
$csvArray = ImportCSV2Array($filename)
foreach ($csvArray as $row)
{
echo $row['column1'];
echo $row['column2'];
echo $row['column3'];
}
Explanation?
The function reads each and every line of the CSV file using
The initial row of data acts like the headings, thereafter a loop iterates over each element of fgetcsv
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ishaan Madan
Ishaan is a qualified and dedicated Technical Project Manager with 7 years of experience building web apps, platforms and leading full stack projects that have a meaningful impact to the company and clients. His technical skill set includes, Python, Django, JavaScript and MySQL.