0

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?

Xfile
  • 674
  • 8
  • 19
  • 1
    [file](http://php.net/manual/en/function.file.php) — Reads entire file into an array –  Nov 02 '12 at 01:08

2 Answers2

1

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()

Xfile
  • 674
  • 8
  • 19
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
  • $arquivo should be replaced with $file and that does it. Thx :) ps: please be patient few mins to accept answer ;) – Xfile Nov 02 '12 at 01:21
  • @Xfile, Sorry, i forgot to translate from Portuguese =). I've updated the answer now. – Marcio Mazzucato Nov 02 '12 at 01:23
  • Thx to you too Marco! It was hard for me to select better answer but ill be using those of Anzicourt. Thx to both of you :))) – Xfile Nov 02 '12 at 01:27
  • @Xfile, No problem, Azincourt gave a nice solution. Take care only about the file size, [see this question](http://stackoverflow.com/questions/2749441/php-fastest-way-possible-to-read-contents-of-a-file) – Marcio Mazzucato Nov 02 '12 at 01:34
  • @ Marcio Simao - Thank you very much Marcio for that link:) Usually data which I insert via this solution are small, but that link is very handy for other tasks in the future. Thx :) – Xfile Nov 02 '12 at 03:28
1

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";
}
Shlomo
  • 3,880
  • 8
  • 50
  • 82