我正试图弄清楚我将如何去缓存数据,我从一个webservice json文件拉到我的页面上,这样我就不会不断地请求这些数据,并把服务器。
我目前正在拉json数据如下:
// jSON URL which should be requested
$json_url = 'http://example.com/datastore.json?toolbar_id='.$persona['toolbar_id'].'';
// jSON String for request
$json_string = '[Json string? What is this]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$result = json_decode($result, true);
$result = $result[0];
从这里我可以拉出关联数组的结果,因为我需要他们。但是如果我要刷新页面,它将召回服务器信息。有解决方案吗?
您可以像对待任何其他缓存文件一样对待它:
- 检查缓存文件是否存在
- 如果是,对照当前
time()
检查filemtime()
- 如果需要刷新,则调用
cURL
,将数据写入缓存文件,继续 - 如果不需要刷新,只需将文件中的数据返回到变量。
它将是相同的JSON,无论PHP是否通过cURL
返回它或PHP是否通过fread()
在缓存文件上返回它。