Page 1 of 1

Assigning lines of a text file to variables

Posted: Sat Feb 28, 2015 11:27 pm
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.

Re: Assigning lines of a text file to variables

Posted: Mon Mar 02, 2015 3:31 pm
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.