Prasad Rajapaksha Prasad Rajapaksha - 3 years ago 95
PHP Question

PHP Search through CSV File

I have a CSV file which is more than 5 MB. As an example like this,

200,"Best of 10","Best of 10","No where"
230,"Best of 10","Best of 10","Love"
4340,"Best of 10","Best of 10","Al Road"

I have plenty of records. I need to get a one record at a time. Assume I need to get the detail of the id 8999. My main question is Is there any method to get exact data record from CSV just like we query in mysql table.

Other than that I have following solutions in my mind to perform the task. What could be the best way.

  1. Read the CSV and load in to array. Then search trough it and get data. (I have to get all records. The order is different that's why I face this issue. Other wise I could get record by record.)

  2. Export CSV to MYSQL database and then query from that table

  3. Read the CSV all the time without loading it to array

If I can search in CSV file in quick way it will be great. Appreciate your suggestions.

Thank you.

Answer Source

I'm not aware if there are any libraries that allow you to directly query a CSV file. If there are, that would be your best bet. If not, here's another solution.

If you want to get details of id 8999, it would be extremely memory inefficient to load in the entire file.

You could do something like this

Read in a line using fgets, explode on comma and check 0th element. If it is not the ID you want, discard and repeat.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download