Really Simple PHP CURL and Cache of JSON Result

When using PHP CURL with a third party API, I’ve found keeping the JSON results in a local cache is easier than constantly querying the service – especially when the API is slow or has query restrictions.

Here’s a great snippet I save in my tool belt and use quite often:

If the API is really slow (I’ve encountered two myself) I suggest splitting the snippets CURL+Cache section and putting it into it’s own file, from there create a CRON command to execute the independent CURL+Cache file. That’ll separate the slow API from your PHP app, and your JSON data will still be up to date in the background.


Comments

  1. Hi! I’m curious about how you would handle LOTS of different API calls? If there are 14,000 calls with different responses, would you store these all as separare files? Store the results in one file and loop through them to see if the result is cached?

  2. This was exactly what I needed to find today. I did have issues write the file using Localhost WAMP Server, but managed to resolve this by using file_put_contents() instead of fwrite().
    At time of writing this I’m not sure on the pros and cons of doing it this way, but hey ho it works and i can push onwards. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *