Skip to content

Instantly share code, notes, and snippets.

@gelanivishal
Created December 25, 2016 03:04
Show Gist options
  • Save gelanivishal/82eba3589abdc4b1ebdeed0726940867 to your computer and use it in GitHub Desktop.
Save gelanivishal/82eba3589abdc4b1ebdeed0726940867 to your computer and use it in GitHub Desktop.
Import CSV to Array with 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 usage
$filename = "test.csv";
$csvArray = ImportCSV2Array($filename)
foreach ($csvArray as $row)
{
echo $row['column1'];
echo $row['column2'];
echo $row['column3'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment