Last active
August 29, 2015 14:16
-
-
Save neo22s/2dceed7cdf5d5b917f82 to your computer and use it in GitHub Desktop.
CSV to Array
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
/** | |
* CSV file to array | |
* @param file $csv | |
* @param array $expected_header | |
* @param boolean $convert_object you want it returned as an object? | |
* @param string $delimiter | |
* @param string $enclosure | |
* @return array | |
*/ | |
public function csv_to_array($csv,$expected_header=NULL,$convert_object = FALSE, $delimiter = "," , $enclosure = '"') | |
{ | |
//open CSV | |
if (file_exists($csv) AND ($handle = fopen($csv, 'r')) !== FALSE) | |
{ | |
$i = 0; | |
$end_array = array(); | |
//line by line | |
while(($data = fgetcsv($handle, 0, $delimiter, $enclosure)) !== FALSE) | |
{ | |
//check the header | |
if ($i == 0 AND is_array($expected_header)) | |
{ | |
if($data != $expected_header) | |
return FALSE; | |
} | |
//not header | |
else | |
{ | |
//return as object | |
if ($convert_object === TRUE) | |
{ | |
$obj = new stdClass(); | |
foreach ($data as $field => $value) | |
{ | |
try { | |
$obj->$expected_header[$field] = $value; | |
} catch (Exception $e) { | |
//got a field that was not in the header :S | |
return FALSE; | |
} | |
} | |
$end_array[$i] = $obj; | |
} | |
else | |
$end_array[$i] = $data; | |
} | |
$i++; | |
} | |
fclose($handle); | |
} | |
return $end_array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment