How to make this csv-reading PHP code more efficient?
Looping on feof is wrong. feof doesn't return return true until after you've hit the end of file. If the read pointer is sitting past the last character and you try to read, feof will return false, but the read will fail. At that point feof will return true.

Example: 

1, a, b, c
2, a, b, c
3, a, b, c


Then reading it:

$rows = array();
while (!feof($fh)) {
    $rows[] = fgetcsv($fh);
}
print_r($rows);


A much more natural (and correct) loop structure is as follows:

while (($row = fgetcsv($fh)) !== false) {
    $rows[] = $row;
}


(You can of course use fgetcsv($fh, 1024) instead of fgetcsv($fh). Just an example.)



As far performance goes, you're doing what you're doing as fast as it can be done. In other words, to get a speed increase, the approach has to change, not the implementation.

There are three main approaches that you can take (that can all be combined as desired): use caching, put the HTML output straight into the first loop so you only do one loop instead of two, and try using a fixed field-size format rather than CSV so parsing overhead can be eliminated.

Putting the HTML output straight into the read loop is very gross from a separation of concerns perspective, and the gains would be minimal compared to the code quality hit.

Likewise, changing to a fixed size format would be a fairly minimal performance gain for quite a bit of headache.

Caching is what you need to do. A primitive approach is to just create an on-disk version of the array and read that rather than the CSV. A slightly more complex but much faster approach is to cache the CSV in memory using apc or even something like memcached (memcached is way overkill, as is arguably apc). Yet another approach is cache the output HTML rather than the array. This allows you to serve a static page rather than regenerate it each request. You can't get any faster than that.

Since the idea remains largely the same, I'll show an example of the simplest one to implement: caching the array.

$csvFilePath = "...";
$cacheFilePath = "...";

if (!file_exists($cacheFilePath) || filemtime($csvFilePath) &gt; $cacheFilePath) {
    $fh = fopen($cacheFilePath, 'r');
    $rows = array();
    while (($row = fgetcsv($fh)) !== false) {
        $rows[] = $row;
    }
    file_put_contents($cacheFilePath, serialize($rows));
} else {
    $rows = unserialize(file_get_contents($cacheFilePath));
}


Though this one is very simple, it's also the least effective. I would cache the entire page output. I would probably use something like Zend_Cache or Symfony's caching component to avoid lots of nasty manual output buffer management. Alternatively, you could write your own simple page cache.