Sean Cooper Sean Cooper - 2 months ago 13
PHP Question

PHP: Reading specific csv lines into a two-dimensional array

I have a file arranged like so:

"url1","info1"

"url2","info2"

"url3","info3" ... all the way up to "url15","info15"


I would like to read the last 10 lines of the file into an array such that $pagelist[0][0] would give url5 and $pagelist[0][1] would give info5.

My current code is as follows:

$file=fopen(csvfile.txt,"r");
$pagelist=array();
$i=0;
$key=0;
while (!feof($file)) {
if ($i >= (count($file)-11)) {
$pagelist[$key]=fgetcsv($file);
$key++; }
$i++;
}
fclose($file)


When I used print_r($pagelist) it seemed to have loaded all the lines of the file into the array instead of just the last 10. Can anyone see what I've done wrong in my code? thanks :)

Answer

The problem with you code is that count($file) is not doing what you think. $file is just a file handle resource, not an array. You end up comparing $i >= -11, which will of course always evaluate to true/

You might try something like this if you want to just use linux to grab the last ten lines (not sure if you are on linux):

$initial_csv = 'csvfile.txt';
$truncated_csv ='csvfile_trun';
$number_of_lines_from_end = 10;
shell_exec('tail -n ' . $number_of_lines_from_end . ' ' . $initial_csv . ' > ' . $truncated_csv);
$file=fopen($truncated_csv,"r");
$pagelist=array();
$i=0;
while (!feof($file)) {
    $pagelist[$i]=fgetcsv($file);
    $i++;
}
fclose($file)

Alternatively, if you don't mind having the entire file in memory (i.e. the file will remain small), you can read the entire file into an array like this.

$csv = 'csvfile.txt';
$number_of_lines_from_end = 10;
$file_array = file($csv);
$line_count = count($file_array);
$start = $line_count - $number_of_lines_from_end - 1;
$pagelist=array();
for ($i = $start; $i < $line_count; $i++) {
    $pagelist[]=fgetcsv($file);
}