Search code examples
phpcsvfgetcsv

How to read a value from 'x'th row and 'y'th column in CSV using PHP?


I am wondering whether it is possible to read a specific value from CSV specifed the row number and column number.

Lets say I want to read data from row number 44 and column number K?

I dont want to parse through the complete CSV. How to read specific data?

Hope I am clear with my question? Any answer would be appreciated.


Solution

  • CSV files have no index, so you would need at least to go to the 44th line and retrieve it:

    $file = new SplFileObject($path);
    $file->setFlags(SplFileObject::READ_CSV);
    $single = new LimitIterator($file, $offset = 43, $limit = 1);
    list($row) = iterator_to_array($single, false);
    $k = 10;
    echo $row[$k];