Subhash
Subhash

Reputation: 383

read a single line in php

I have a file with 20 lines , with 3 numbers in each line... separated by spaces.. I just need to read 1 line at a time so that i can store those 3 number in an array... and use them in the code...the next time it should read the 2nd line and store in the array..and soon..how should i proceed .. i have tried fgets

 $fh = fopen($argv[1], "r");
    while($i<=20)
    {
    $line = trim($fh);
    $str=explode($line);
    }

and this as well...

$i=1;
while($i<=20)
{
$lines = file($argv[1], FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
foreach ($lines as $l){}

Upvotes: 0

Views: 288

Answers (3)

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

<?php

function ReadLineNumber($file, $number)
{
    $handle = fopen($file, "r");
    $i = 0;
    while (fgets($handle) && $i < $number - 1)
        $i++;
    return fgets($handle);
}
?>

this example for Read single line from a big text file .try this

Upvotes: 2

Joshua Kissoon
Joshua Kissoon

Reputation: 3309

You can use fgets like this:

$fh = fopen($argv[1], "r");
if ($fh) 
{
    while (($line = fgets($fh)) !== false) 
    {
        // process the line read.
    }
} 
else 
{
    // error
} 

// Close the handle
fclose($fh);

Upvotes: 0

Zebra North
Zebra North

Reputation: 11482

Use fgetcsv() - don't forget to set the delimiter to space.

Upvotes: 4

Related Questions