Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP reading a csv file effectively

Tags:

php

There are a few ways to read CSV files with PHP. I used to use the explode function to put each line into an array and then explode commas and use trim to remove any quotation marks from around the data. It was messy...

In PHP 5 there's now fgetcsv and *str_getcsv*... I'm guessing this is the best way to go about it these days so I've whipped together some code...

$fp = fopen($csv_file['file_path'], 'r');       
while (($data = fgetcsv($fp, 0, "\r", '"', "\r")) !== FALSE) {
    $num = count($data);
    for ($c=0; $c < $num; $c++) {
        print_r(str_getcsv($data[$c]));
    }
}

It seems to work but is there a more fail safe approach? For example making it work whether line breaks are \n or \r...

Any input you can give would be awesome!

like image 949
Ben Sinclair Avatar asked Oct 06 '11 02:10

Ben Sinclair


1 Answers

There is a function for reading files in line-wise: file(), which also works on both linebreak types.

And the shortest method to read in the whole CSV file is:

$data = array_map("str_getcsv", file($filename));

Not sure what your $num = count() was about.

like image 65
mario Avatar answered Sep 29 '22 07:09

mario