Load a CSV file and transform to an array. Simple helper for quick and dirty scripting.
<? | |
/** | |
* 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