我正在使用Google的Calculator API。我必须将动态值传递给google网址,如下所示:
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
但是我从谷歌获得以下例外。
Warning: file_get_contents(http://www.google.com/ig/calculator?hl=en&q=13,000,000pkr=?cad) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable in /home/..../public_html/config/config.php on line 48
我的功能是:
function exchangeRate($amount, $currency, $exchangeIn) {
$url = 'http://www.google.com/ig/calculator?hl=en&q=' . urlEncode($amount . $currency . '=?' . $exchangeIn);
$data = file_get_contents($url);
if(!$data) {
throw new Exception('Could not connect');
}
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
$array = $json->decode($data);
if(!$array) {
throw new Exception('Could not parse the JSON');
}
if($array['error']) {
throw new Exception('Google reported an error: ' . $array['error']);
}
return number_format($array['rhs']);
}
echo exchangeRate('9,200,000', 'pkr', 'cad')
我的代码有什么问题或者这个google api有什么问题吗?
由于
答案 0 :(得分:0)
我还使用Google的Calculator API创建了货币计算器。以下是我的代码。
用法:
只需使用您自己的网址,例如: yourdomain.com/file.php?from=USD&to=EUR&q=10
PHP脚本:
<?php
session_start();
if(isSet($_GET['from']) && isSet($_GET['to']) && isSet($_GET['q'])) {
$from = preg_replace('/[^A-Z]/','',$_GET['from']);
$to = preg_replace('/[^A-Z]/','',$_GET['to']);
$q = preg_replace('/[^0-9\.]/','',$_GET['q']);
echo currency($from,$to,$q);
}
function currency($from_Currency,$to_Currency,$amount) {
$cookieName = md5("$from_Currency|$to_Currency|$amount");
if(isSet($_COOKIE["$cookieName"])) {
echo $_COOKIE["$cookieName"];
}
else {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , $_SERVER['HTTP_USER_AGENT']);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = html_entity_decode($rawdata);
$data = str_replace(array('lhs','rhs','error','icc',': '),array('"lhs"','"rhs"','"error"','"icc"',':'),$data);
$row = json_decode($data,true);
if(preg_match('/million/',$row['rhs'])) {
$x = 1000000;
}
else if(preg_match('/billion/',$row['rhs'])) {
$x = 1000000000;
}
else {
$x = 1;
}
$result = preg_replace('/[^0-9\.]/','',$row['rhs']);
$kurs = $result * $x;
if($row['icc'] == 'true') {
setcookie("$cookieName", number_format($kurs,2), time()+3600);
return number_format($kurs,2);
}
else {
return "Not available";
}
}
}
?>