Skip to content

Instantly share code, notes, and snippets.

@monishnarwani
Created October 6, 2018 05:30
Show Gist options
  • Save monishnarwani/131595971cf7b9c9189ce4d8faf09f87 to your computer and use it in GitHub Desktop.
Save monishnarwani/131595971cf7b9c9189ce4d8faf09f87 to your computer and use it in GitHub Desktop.
Simple php class to parse CSV file data into array with headers
<?php
class CSVHelper
{
// Build wonderful things
public static function parseCSV($fileName)
{
$extractData = [];
$csvArray = [];
if($fileName) {
$fp = fopen($fileName, 'r');
if($fp) {
while ($row = fgetcsv($fp)) {
$csvArray[] = $row;
}
fclose($fp);
$headers = [];
foreach($csvArray as $key=>$data) {
if($key == 0) {
$headers = $data;
continue;
}
$temp = [];
foreach($data as $key1=>$value) {
$temp[$headers[$key1]] = $value;
}
$extractData[] = $temp;
}
}
}
return $extractData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment