Created
December 25, 2016 03:04
-
-
Save gelanivishal/82eba3589abdc4b1ebdeed0726940867 to your computer and use it in GitHub Desktop.
Import CSV to Array with PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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