Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and CSV file - how to detect end of line? [duplicate]

Possible Duplicate:
how to extract data from csv file in php

I have some data in XLS, I save them as CSV, the delimiter is **comma*. Then I am trying to load the data from this CSV file:

$input = explode("\r\n", fread($file, filesize("my_data.csv")));
print_r($input);

The output:

Array ( [0] => data from the CSV file)

This is the problem - in the array is always just one item, where are printed out all data from the CSV file. How is that possible? Why isn't in the array as much items as is rows in the CSV file?

Also, I've tried to change "\r\n" for "\n", but it's the same.

What I am trying to do - load each line from the CSV file and this each line to process.

EXAMPLE OF THE FILE:

a,b,c,d
e,f,g,h

OUTPUT:

a,b,c,d e,f,g,h

like image 272
user984621 Avatar asked Dec 20 '12 17:12

user984621


1 Answers

I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: http://php.net/manual/en/function.fgetcsv.php

 if (($handle = fopen($file, "r")) !== FALSE) {
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row = implode (",",$data); //puts back together the row from the csv
        echo $row. "\n"; //assuming you want a visual linebreak on console, add the \n
     }
    fclose($handle);
 }  
like image 118
Ray Avatar answered Oct 05 '22 21:10

Ray