Created
January 12, 2020 22:04
-
-
Save barryhughes/bcd31012409995eed75189cc4f0ac39b to your computer and use it in GitHub Desktop.
Load a CSV file and transform to an array. Simple helper for quick and dirty scripting.
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
<? | |
/** | |
* Given a path to a valid CSV file, returns an array containing the data | |
* (an array of arrays, with outer arrays representing the rows and inner | |
* arrays representing the columns). | |
* | |
* @param string $path_to_csv | |
* | |
* @return array | |
*/ | |
function read_csv( string $path_to_csv ): array { | |
$data = []; | |
if ( ! file_exists( $path_to_csv ) ) { | |
return []; | |
} | |
if ( ! $file_handle = fopen( $path_to_csv, 'r' ) ) { | |
return []; | |
} | |
while ( ! feof( $file_handle ) ) { | |
$data[] = fgetcsv( $file_handle, 32768 ); | |
} | |
fclose( $file_handle ); | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment