Bob Flemming
Bob Flemming

Reputation: 466

Caching images locally from external json feed

I'm currently working on a site that uses wordpress feeds to display posts. All seems to be working fine, however, the page load is very slow. I have implemented my own caching which means the the feeds will only be queried one every two hours (see code below).

$cacheFile =  'cached-data/data.txt';

$cacheData = file_get_contents($cacheFile);   
$two_hours = time() - 1;
$cacheTime = filemtime($cacheFile);

if ($cacheTime > $two_hours)
{
    $dataArray = $cacheData;
}
else
{
    //get data
    $historyData = file_get_contents('http://www.mysite.co.uk/feed/json?image=thumbnail&posts_per_page=5');
    $historyData = json_decode($historyData,true);

    $animalData = file_get_contents('http://www.mysiteothersite.co.uk/feed/json?image=thumbnail&posts_per_page=5');
    $animalData = json_decode($animalData,true);


    $dataArray = array_merge($historyData['posts'],$animalData['posts']);       

    $dataArray = json_encode($dataArray);

    $newCachFile = fopen($cacheFile, 'wb');
    fwrite($newCachFile, $dataArray);
    fclose($newCachFile);


}

$dataArray = json_decode($dataArray,ARRAY_A);

This speeds things up but the image load time is still rather slow. Therefore, I want to implement a function which downloads the images once an hour and modifies the the downloaded json so it replaces the image URLs to locally hosted images instead of the images being downloaded from their server.

Can anyone advice me on how to save the images locally?

Thanks

Upvotes: 0

Views: 189

Answers (1)

David Normington
David Normington

Reputation: 847

You can use file_get_contents to grab the image data and file_put_contents to save the image to your file system. Then modifying the JSON is as easy as changing the value in the JSON decoded array, then re-encoding it.

//example for JPEG image
$image = file_get_contents($imageUrl);
file_put_contents('MyImage.jpg', $image);

Upvotes: 1

Related Questions