Read single line from file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
riversr54
Forum Newbie
Posts: 9
Joined: Wed Feb 24, 2010 9:02 am

Read single line from file

Post 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
Alkis
Forum Commoner
Posts: 31
Joined: Fri Mar 26, 2010 8:41 am

Re: Read single line from file

Post by Alkis »

There is a specific function for csv files, it is called fgetcsv. Hope that helps
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Read single line from file

Post by s.dot »

Yes, fgetcsv() is nice. Also, file() will read a file line by line.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
riversr54
Forum Newbie
Posts: 9
Joined: Wed Feb 24, 2010 9:02 am

Re: Read single line from file

Post 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?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Read single line from file

Post by s.dot »

Yes.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
riversr54
Forum Newbie
Posts: 9
Joined: Wed Feb 24, 2010 9:02 am

Re: Read single line from file

Post by riversr54 »

Got it working, thanks for the help.

rivers
Post Reply