Code Examples

Convert CSV file to Array in PHP

programming

In this code example, we will read a simple CSV file, convert it to Array, then display its content on a web page.

    public function index()
    {
        //read the csv file into an array 
        $csvFile = storage_path() . "\app\simple.csv";
        $csv = $this->csvToArray($csvFile);
        //render the array with print_r 
        echo '<pre>';
        print_r($csv);
        echo '</pre>';
    }

    private function csvToArray($csvFile)
    {
        $file_to_read = fopen($csvFile, 'r');
        // skip the header row
        fgets($file_to_read);
        while (!feof($file_to_read) ) {
            $lines[] = fgetcsv($file_to_read, 1000, ',');
        }
        fclose($file_to_read);
        return $lines;
    }