Assigning lines of a text file to variables

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
Columbo
Forum Newbie
Posts: 5
Joined: Sun Aug 09, 2009 1:55 pm

Assigning lines of a text file to variables

Post by Columbo »

I have a text file that consists of 200 lines that are delimited with the # sign. Each five lines in the text file make up one record for a mysqli database. That means, of course, that the 200 lines in the text file make up 40 records. I am trying to find a way to read 5 lines of text at a time, (1 record), and assign them to variables so that I can INSERT INTO the MySQLi database, until all 40 records in the text file have been read and inserted.

I can get it to display each record on the screen using this code:

Code: Select all


$handle = fopen("testfile.txt", "rb");
   $delimiter = "#";
   while (!feof($handle) ) {
          for ($x = 1; $x < 5; $x++) {
            $line = fgets($handle);
            $data = explode($delimiter, $line);

            foreach($data as $v) {
	   echo nl2br($v) . "\n\n";
	 }
        }
    }
    fclose($handle);

but I can’t figure out how to assign them to variables to insert into the MySQLi database.



Any help would be greatly appreciated.



Thanks in advance.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Assigning lines of a text file to variables

Post by requinix »

Use fgetcsv for reading lines. You aren't using a comma-separated format, but #-separated is basically the same thing.

If the five lines are supposed to be taken together then don't bother with the for loop and just read the five lines normally. Then you'll have five arrays. Construct the appropriate query(ies), however you would do that I have no idea what they look like, from the five arrays.
Post Reply