Page 1 of 1

Read single line from file

Posted: Fri Mar 26, 2010 9:16 am
by riversr54
I'm new to PHP so this may be a simple answer but I can't seem to figure it out.

I am trying to read a text file that was produced by saving an Excel spreadsheet in csv format. The data looks like this.

item1,item2,item3
item1,item2,item3

The length of each line is a random length. I wold like to read the file one line at a time but fgets doesn't seem to understand the end-of-line and just keeps reading right past it into the next line. I tried reading in a standard number of characters for each line, then using explode to save the parts into an array but I can't seem to find anything that it will recognize as an end of line character. I also tried using rtrim to trim off any trailing white space but that didn't work either.

Bottom line is I need some way of reading lines from a file that have random lengths and I need the read to recognize the end of line so that it doesn't read into the next line. Is there a simple solution that I'm missing?

thanks,
rivers

Re: Read single line from file

Posted: Fri Mar 26, 2010 9:25 am
by Alkis
There is a specific function for csv files, it is called fgetcsv. Hope that helps

Re: Read single line from file

Posted: Fri Mar 26, 2010 9:27 am
by s.dot
Yes, fgetcsv() is nice. Also, file() will read a file line by line.

Re: Read single line from file

Posted: Fri Mar 26, 2010 9:54 am
by riversr54
Ok, fgetcsv sounds like the perfect solution, but....

When I use it, I'm getting a really strange result(strange to me anyway).

My code:

$s=fgetcsv($fh, 1024);
echo $s;

The output of this simple code says:

ARRAY

as if it has read the string into an array. Is that true?

Re: Read single line from file

Posted: Fri Mar 26, 2010 9:56 am
by s.dot
Yes.

Re: Read single line from file

Posted: Fri Mar 26, 2010 10:59 am
by riversr54
Got it working, thanks for the help.

rivers