How To Easily Read Csvs In PHP

Sometimes we just need to read in a csv file in php. I’ve tried using thephpleague’s csv package but it is over engineered in my opinion to do something so basic. Really, I want something similar to how file_get_contents gives me the entire content of the file but for the csv (in array format).

Here is a snippet I made that reads in a csv and returns an array of results.

    function csv_to_array($path, $hasHeader = true) {
        $results = [];

        $handle = fopen($path, 'r');

        if ($hasHeader) {
            $header = fgetcsv($handle, 1000, ",");
        }

        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            if ($hasHeader) {
                $results[] = (object) array_combine($header, $data);
            } else {
                $results[] = $data;
            }
        }

       fclose($handle);

       return $results;
    }
post by K.D. on 03/21/2019