像這樣的東西應該工作。
function apiCall($type, $params=array())
{
//building up the url parameters
$args=array();
foreach($params as $field=>$value)
{
// Seperate each column out with it's corresponding value
$args[]=$field.'='.str_replace(' ', '+',$value).'';
}
// Create the query
$url = $this->baseurl.$type.'?'.implode('&',$args);
//check if CURL is available, if so use curl to make the call, otherwise get the file content via file_get_contents()
if (function_exists('curl_init'))
{
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// Removes the headers from the output
curl_setopt($ch, CURLOPT_HEADER, 0);
// Return the output instead of displaying it directly
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0');
// Execute the curl session
$result = curl_exec($ch);
$errno = curl_errno($ch);
// CURLE_SSL_CACERT || CURLE_SSL_CACERT_BADFILE
if ($errno == 60 || $errno == 77) {
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ca_chain_bundle.crt');
$result = curl_exec($ch);
}
// Close the curl session
curl_close($ch);
$res = json_decode($result, true);
return $result;
}
else
{
// fallback if we don't have CURL or if ifs curently not available (whysoever)
// A litte slower, but (usually) gets the job done
$res = file_get_contents($url);
return json_decode($res, true);
}
}
用法是與此類似:
$res = $this->apiCall('search', array('term'=>$term, 'entity'=>$entity, 'country'=>$country));
這將返回一個關聯數組。
curl_setopt($ ch,CURLOPT_POST,0);所以這意味着GET ?,我覺得奇怪,你不能明確寫入GET – bobo2000
這是正確的朋友。對於GET請求,它是0和1的POST。其實默認情況下它是GET。 – Janaki