Last active
January 3, 2017 08:14
-
-
Save xappz/5dff4857af1d2aac058b3e77cbec3429 to your computer and use it in GitHub Desktop.
Reading CSV files in 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 | |
//An elegant way to read CSV data in PHP. | |
//Tested with PHP7 | |
//BTW, you can quickly generate some test data at https://www.mockaroo.com/ | |
error_reporting(-1); | |
const CSV_FILE = "data.csv"; | |
const CSV_MAP = array( | |
'serial', | |
'first-name', | |
'last-name' | |
); | |
class CsvUtils { | |
public static function readCsvFile($fileName, $callback) { | |
try { | |
$file = new \SplFileObject($fileName); | |
} catch (\RuntimeException $e) { | |
throw new \Exception("Cannot open $fileName"); | |
} | |
while (!$file->eof()) { | |
$line = trim($file->fgets()); | |
if (empty($line)) { | |
continue; | |
} | |
$data = explode(",", $line); | |
foreach ($data as &$d) { | |
$d = trim($d); | |
} | |
call_user_func($callback, $data); | |
} | |
} | |
} | |
CsvUtils::readCsvFile(CSV_FILE, function($data) { | |
$data = array_combine(CSV_MAP, $data); | |
print_r($data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment