6

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

Community
  • 1
  • 1
user984621
  • 46,344
  • 73
  • 224
  • 412
  • 2
    Use the built in fgetcsv() function for reading CSV data – Mark Baker Dec 20 '12 at 17:21
  • Any reason you are not using http://php.net/manual/en/function.fgetcsv.php ? Don't try to parse CSV data by yourself -you'll be in for a world of pain with anything more complex than a simple list of numbers. – Michael Berkowski Dec 20 '12 at 17:21
  • 1
    But guys, how do you solve the last item on the row? Because, this last item has any comma in the end, so the last item is merged with the first item on the second line. – user984621 Dec 20 '12 at 17:28
  • @user984621: CSV reading is a solved problem. Use the `fgetcsv` function that has already been written, tested and debugged, rather than writing your own code that you will have to write, test and debug. – Andy Lester Dec 20 '12 at 17:29
  • Guys, sorry if this is too stupid question and that's the reason why you want to close the question, but above I described the problem for which I just didn't figure out... – user984621 Dec 20 '12 at 17:36

2 Answers2

4

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);
 }  
Ray
  • 40,256
  • 21
  • 101
  • 138
  • I don't know if it's a bug or, but when I try this, so the last item in the line has not a comma in the end - what getting me into troubles... because I don't get expected output. – user984621 Dec 20 '12 at 17:26
  • Ray, please checkout the OP, this is the output that I get if I will use this snippet -- the letter `d` and `e` are merged into one item. That's my whole problem that I don't know how to solve. – user984621 Dec 20 '12 at 17:34
0

How I solved this issue:

In the XLS file, before exporting the file into CSV, I added in the end of sheet one more column with the char '.

user984621
  • 46,344
  • 73
  • 224
  • 412