我得到了以下代码来通过API检索一些json:
public function get_json($jsonurl, $ttl = 3600) {
$cache_file = $this->cache_dir . DIRECTORY_SEPARATOR . md5($jsonurl);
$function = __FUNCTION__;
if (file_exists($cache_file) && filemtime($cache_file) < time() - $ttl) {
unlink($cache_file);
}
if (!file_exists($cache_file)) {
file_put_contents($this->cache_dir . DIRECTORY_SEPARATOR . 'cache.log', $jsonurl . ': ' . $cache_file . "\n", FILE_APPEND);
try{
$response = $this->fetchUrl($jsonurl);
} catch(Exception $ex){
return true;
}
file_put_contents($cache_file, $response);
}
elseif(file_exists($cache_file)){
$response = file_get_contents($cache_file);
}
$json_output = json_decode($response, true);
if(empty($json_output)){
unlink($cache_file);
}
return $json_output;
}
private function fetchUrl($url) {
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
));
$response = curl_exec($curl);
if (!$response) {
$exception = new Exception(curl_error($curl) ?: 'Empty response', curl_errno($curl));
curl_close($curl);
throw $exception;
}
curl_close($curl);
return $response;
}
在本地它工作正常,但在实时服务器上我检索NULL。当我将jsonurl放入浏览器时,它返回有效的json。那么它可能与fetchUrl函数和curl_setopt_array有关吗?
请帮助我疯狂!