Saturday 23 July 2016

PHP Function to read file to CSV array

Use these simple php function to read csv and tsv files to a php array. We can read data from a comma separated file and tab separated file and make a php array with this simple function.

function readCsvTsvToArray($filepath, $preserveKeys=false, $filetype) {
        if($filetype=="csv") $separator=",";
        else if($filetype=="tsv") $separator="  ";
        $array = array();
     
        if (!file_exists($filepath)){ return $array; }
        $fileContent = file($filepath);
     
        for ($x=0; $x<count($fileContent); $x++) {
            if (trim($fileContent[$x]) != '') {
                $line = explode("$separator", trim($fileContent[$x]));
                if ($preserveKeys) {
                    $key = array_shift($line);
                    $array[$key] = $line;
                }
                else { $array[] = $line; }
            }
        }
        return $array;
}

No comments:

Post a Comment