www.webdeveloper.com
Results 1 to 6 of 6

Thread: How can I read a txt file line by line?

  1. #1
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364

    How can I read a txt file line by line?

    I have a .txt file which I am reading with php (fread). I want to print each line separately (so I can write a function to print only specified lines). How do I do this? How can I read this file line by line?

    Also, if I have a delimiter, how can I put each field between the delimiters in its own array?

    Any help on this will be much, much appreciated! Thanks!

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,175
    If you use file() to read the file, then you will have an array of lines which you can loop through (via foreach()) or call specific line via the array index.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    May 2003
    Posts
    599
    Quote Originally Posted by NogDog View Post
    If you use file() to read the file, then you will have an array of lines which you can loop through (via foreach()) or call specific line via the array index.
    I agree. This is the way to do it if you are trying to read a file "line by line" since file() automatically splits on line returns. It can really help to simplify your code since you would not have to fopen() or fclose() the file.

    fread() would be more appropriate if you were trying to read a file by bytes or some other increment.

    as far as the delimeters to get the fields to another array, uisng the explode() function within the foreach loop mentioned above may help facilitate that.
    Last edited by hastx; 11-01-2009 at 06:33 PM.
    We do precision guesswork

  4. #4
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364
    Thanks!

    Hmm... could anyone point me to some cample code I could use to accomplish this?

  5. #5
    Join Date
    May 2006
    Location
    the netherlands
    Posts
    454
    Free Scripts (PHP, Javascript, MySQL), homemade in the Excudo Devshed
    Create your own personal Startpage for free

  6. #6
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364
    Thanks, I think I got it though.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles