Read Contents from CSV and TSV files to PHP Array

by Sasikumar 2014-07-01 18:10:02

To read contents from Comma Separated Files (CSV) and Tab Separated Files (TSV) use the following php function:

PHP Function:
function read_file_data_to_array($filepath, $load_keys=false, $filetype)
{
        if($filetype=="csv") $separator=",";
        else if($filetype=="tsv") $separator="	";
        $array = array();
     
        if (!file_exists($filepath)){ return $array; }
        $content = file($filepath);
     
        for ($x=0; $x < count($content); $x++){
            if (trim($content[$x]) != ''){
                $line = explode("$separator", trim($content[$x]));
                if ($load_keys){
                    $key = array_shift($line);
                    $array[$key] = $line;
                }
                else { $array[] = $line; }
            }
        }
        return $array;
}
Usage Example:
/* To Read Tab Separated Files (tsv) */
$tsv_data_array = read_file_data_to_array("filepath", false, "tsv");

/* To Read Comma Separated Files (csv) */
$csv_data_array = read_file_data_to_array("filepath", false, "csv");

/* Output Array */
print_r($tsv_data_array);
print_r($csv_data_array);
1626
like
0
dislike
0
mail
flag

You must LOGIN to add comments