Created
November 21, 2019 23:03
-
-
Save AEROGU/562b23611fbbbf283149eeb3bc518e83 to your computer and use it in GitHub Desktop.
Read CSV with 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 | |
/** | |
* Read character separated values file like CSV, TSV, etc., | |
* If $a_asocciative==true returns asocciative matrix using | |
* the first row as column names. | |
* | |
* Example: print_r(csv2matrix("ocr_result.tsv", "\t")); | |
* | |
* @author Arturo E. Rosas Gutiérrez <https://github.com/AEROGU> | |
* @license MIT | |
* | |
* @param string $a_filename | |
* @param string $a_separtor | |
* @param boolean $a_asocciative | |
* @return array Matrix data | |
*/ | |
function csv2matrix($a_filename, $a_separtor, $a_asocciative=true){ | |
$line = 0; | |
$file = fopen($a_filename, "r"); //Open file for reading | |
$matrix = array(); | |
$column_names = array(); | |
while (($row = fgetcsv($file, 0, $a_separtor)) == true) { // Ride rows | |
$num_colums = count($row); // Columns number in current row | |
if ($line == 0){ | |
for ($colum = 0; $colum < $num_colums; $colum++) { | |
$column_names[$colum] = $row[$colum]; | |
} | |
} else { | |
//Ride colums | |
for ($colum = 0; $colum < $num_colums; $colum++) { | |
$matrix[$line][$a_asocciative ? $column_names[$colum] : $colum] = $row[$colum]; | |
} | |
} | |
$line++; // Current row number | |
} | |
//Cerramos el archivo | |
fclose($file); | |
return $matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment