2014-02-26 28 views
0

我目前正在使用WordPress訂閱源來顯示帖子。所有似乎工作正常,但是,頁面加載非常緩慢。我已經實現了自己的緩存,這意味着只能每兩小時查詢一次提要(請參閱下面的代碼)。從外部json訂閱源本地緩存圖片

$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); 

這可以加快速度,但圖像加載時間仍然很慢。因此,我希望實現一項功能,即每小時下載一次圖像並修改下載的json,以便將圖像URL替換爲本地託管的圖像,而不是從服務器下載的圖像。

任何人都可以告訴我如何在本地保存圖像?

感謝

回答

1

您可以使用file_get_contents來獲取圖像數據和file_put_contents將圖像保存到文件系統。然後修改JSON就像更改JSON解碼數組中的值一樣簡單,然後對其進行重新編碼。

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

謝謝。我自己就明白了這一點!作品一種享受 –