Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Created January 12, 2020 22:04
Show Gist options
  • Save barryhughes/bcd31012409995eed75189cc4f0ac39b to your computer and use it in GitHub Desktop.
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.
<?
/**
* 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