Xfile
Xfile

Reputation: 684

Grabbing data from a text file in a "line per line" manner - and sending those into mysql using PHP

Ok I have a data similar like this, written in a single text file..

BOX,12

CAN,99

.... and so on.

Now I want to execute those into mysql tables using explode() what will not be a problem.

But anyway, any ideas how can I grab row per row (line per line) from a text file into PHP?

Upvotes: 0

Views: 95

Answers (2)

Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

You can do this:

// Trying to open TXT file
if( $file = fopen('file.txt', 'r') )
{
    // Loop until the End Of File
    while( ! feof($file) )
    {
        // Get current line
        $line = fgets($file);

        echo $line . '<br />';
    }

    // Closing TXT file
    fclose($file);
}
else
    echo 'fopen() fail';

For more detais about the functions:

fopen()
feof()
fgets()
fclose()

Upvotes: 1

Shlomo
Shlomo

Reputation: 3990

Read it like this:

$lines = file('my/file/text.txt');

foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . $line . "<br>\n";
}

Upvotes: 1

Related Questions