Read CSV from end to beginning in PHP

坚强是说给别人听的谎言 提交于 2021-01-27 14:42:24

问题


I am using PHP to expose vehicle GPS data from a CSV file. This data is captured at least every 30 seconds for over 70 vehicles and includes 19 columns of data. This produces several thousand rows of data and file sizes around 614kb. New data is appended to end of the file. I need to pull out the last row of data for each vehicle, which should represent the most the recent status. I am able to pull out one row for each unit, however since the CSV file is in chronological order I am pulling out the oldest data in the file instead of the newest. Is it possible to read the CSV from the end to the beginning? I have seen some solutions, however they typically involve loading the entire file into memory and then reversing it, this sounds very inefficient. Do I have any other options? Thank you for any advice you can offer.

EDIT: I am using this data to map real-time locations on-the-fly. The data is only provided to me in CSV format, so I think importing into a DB is out of the question.


回答1:


With fseek you can set the pointer to the end of the file and offset it negative to read a file backwards.




回答2:


If you must use csv files instead of a database, then perhaps you could read the file line-by-line. This will prevent more than the last line being stored in memory (thanks to the garbage collector).

$handle = @fopen("/path/to/yourfile.csv", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // old values of $last are garbage collected after re-assignment
        $last = $line;
        // you can perform optional computations on past data here if desired
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);

    // $last will now contain the last line of the file.
    // You may now do whatever with it
}

edit: I did not see the fseek() post. If all you need is the last line, then that is the way to go.



来源:https://stackoverflow.com/questions/6239408/read-csv-from-end-to-beginning-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!