zadubz
zadubz

Reputation: 1301

how can I get php to read 5 lines instead of the whole .csv file?

$file_handle = fopen("ticker.csv", "r");  while (!feof($file_handle) ) {

  $line_of_text = fgetcsv($file_handle, 1024);

  print '<div class="ticker_price">'. $line_of_text[7] . "</div>";
                                                                                                       }
fclose($file_handle);

How can I read a limited number of lines from the column 7 inside the .csv file

Upvotes: 1

Views: 3801

Answers (5)

Isius
Isius

Reputation: 6974

You can use 'file' to read the file into an array, then just grab each line, explode it into another array, then grab the index you want.

Upvotes: 0

Joe Green
Joe Green

Reputation: 1777

The fgetcsv function will give you an array representing one row. So to get at the nth column you have to loop through the rows and grab the nth value.

So if you wanted the 7th column up to the tenth row you could do

$row_from = 0;
$row_to = 10;
$row_counter = 0;
$7th_array = array();
while ($line = fgetcsv($file_handle, 1024)) {
   if ($row_from <= $row_counter && $row_to >= $row_counter)
      $7th_array[] = $line[6];
   $row_counter++;
}

and you would have all the values from the 7th column in $7th_array.

Upvotes: 0

gintas
gintas

Reputation: 2178

You can use fgets to read file line by line and parse each line with str_getcsv

http://php.net/manual/en/function.fgets.php

http://uk.php.net/manual/en/function.str-getcsv.php

Upvotes: 0

h00ligan
h00ligan

Reputation: 1481

A small change to your code should read a maximum of five lines:

$maxLines = 5;
$file_handle = fopen("ticker.csv", "r");

for ($i = 0; $i < $maxLines && !feof($file_handle); $i++)
{
    $line_of_text = fgetcsv($file_handle, 1024);
    print '<div class="ticker_price">'. $line_of_text[7] . "</div>";
}
fclose($file_handle);

Upvotes: 5

Jared
Jared

Reputation: 12524

Take a look at fgets()

http://www.php.net/manual/en/function.fgets.php

It should be just what you need.

Upvotes: 1

Related Questions