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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With