Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop read each line of a file to its own array [duplicate]

I have a text file, it can vary in number of lines, but will always have 24 tab deliberated entries on each line.

4 of these entries are dates, but they're not in the normal YYYY-MM-DD format example: "2013-03-11T20:35:33+00:00" so I use substr and thats all fine. However currently I pass all the data from the file to a table then take each date do the substr and UPDATE the fields, to then pass all this table to another but with the date field types as "DATE" as first time round they can't due to "2013-03-11T20:35:33+00:00".

The point I'm getting at is, I'd like to read each line into an array apply the substr to the dates which will always be in the same position then, pass the array into the table, so the data type for the column can be DATE from the get go.

I just can't seem to figure out how to loop round for each line in the file. I can get the first line (as I need to delete that), I've read that getting a specific line is impossible or hard but I just need it to loop through them periodicity.

I currently have

while ($DateRow = mysql_fetch_array($DateQuery, MYSQL_ASSOC))

which loops for each row in the table but I don't know how or if this can be implimented for the file lines.

Many thanks.

like image 873
Vereonix Avatar asked Oct 21 '13 20:10

Vereonix


2 Answers

You're using a database function to loop through a database table - that's fine. To get file contents into an array, use file(). Example:

$filename = 'info.txt';
$contents = file($filename);

foreach($contents as $line) {
    echo $line . "\n";
}
like image 187
scrowler Avatar answered Nov 10 '22 13:11

scrowler


All of the substr() stuff could be made easier with strtotime() and/or date() I'm sure:

$lines = file('/path/to/file.txt');
foreach($lines as $row) {
    //whatever here
}
like image 42
AbraCadaver Avatar answered Nov 10 '22 13:11

AbraCadaver