0
我在獲取正在使用的API的緩存時遇到了一些問題。使用php獲取API緩存的問題
下面的代碼工作得很好,當$cache->$do_url
只是一個沒有數組的ID和KEY的文件,但我遇到的問題是我必須傳遞API ID和密鑰以便API吐出我需要的信息。
namespace Gilbitron\Util;
class SimpleCache {
// Path to cache folder (with trailing /)
public $cache_path = 'cache/';
// Length of time to cache a file (in seconds)
public $cache_time = 86400;
// Cache file extension
public $cache_extension = '.cache';
// This is just a functionality wrapper function
public function get_data($label, $url)
{
if($data = $this->get_cache($label)){
return $data;
} else {
$data = $this->do_curl($url);
$this->set_cache($label, $data);
return $data;
}
}
public function set_cache($label, $data)
{
file_put_contents($this->cache_path . $this->safe_filename($label) . $this->cache_extension, $data);
}
public function get_cache($label)
{
if($this->is_cached($label)){
$filename = $this->cache_path . $this->safe_filename($label) . $this->cache_extension;
return file_get_contents($filename);
}
return false;
}
public function is_cached($label)
{
$filename = $this->cache_path . $this->safe_filename($label) . $this->cache_extension;
if(file_exists($filename) && (filemtime($filename) + $this->cache_time >= time())) return true;
return false;
}
//Helper function for retrieving data from url
public function do_curl($url)
{
if(function_exists("curl_init")){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
} else {
return file_get_contents($url);
}
}
//Helper function to validate filenames
private function safe_filename($filename)
{
return preg_replace('/[^0-9a-z\.\_\-]/i','', strtolower($filename));
}
}
$cache = new SimpleCache();
$cache->cache_path = 'cache/';
$cache->cache_time = 86400;
if($data = $cache->get_cache('label')){
$data = json_decode($data);
} else {
$data = $cache->do_curl('http://data.leafly.com/locations/denver-relief/reviews?skip=0&take=12',
array(
'headers' => array(
'app_id' => 'MYIDHERE',
'app_key' => 'MYKEYHERE'
)
)
);
$cache->set_cache('label', $data);
$data = json_decode($data);
}
print_r($data);
任何想法?
使用答案
對於任何人通過谷歌的類似問題找編輯,我找到了答案。
我改變了do_curl
線拉動的API連結此:
$data = $cache->do_curl('http://data.leafly.com/locations/denver-relief/reviews?skip=0&take=12');
,並添加在do_curl
功能下面的行頭拉app_id
和app_key
信息需要:
curl_setopt($ch, CURLOPT_HTTPHEADER,array('app_id: MYAPPID','app_key: MYAPPKEY'));
恭喜!好像你在我輸入它之前幾秒鐘就找到了你的解決方案:)儘管如此,仍然有一個看看,因爲它包含了一個關於如何通過將標題作爲變量傳遞給變量的方法使得你的curl請求更具動態性的建議 –
@ T3H40謝謝!是的,在我發佈並發現它之後,我正在進行一些搜索。儘管你給出了正確的答案,但要將你的答案標記爲正確答案。 –
謝謝一堆!很高興我(可以)幫助:) –