货币兑换美元兑换INR

时间:2012-02-20 13:31:51

标签: php

我想将货币从美元转换为INR,美元的价值从网址反转,我想根据当前汇率将其转换为INR。  这是第一个代码:

<?php 
 require_once('currency.php');

 $val=$_GET["val"];

 echo currency($val);

 ?>

,第二个代码是:

<?php

function currency($val) {
$amount = $val;

 $url = "http://www.google.com/ig/calculator?hl=en&q=$amountUSD=?INR";
 $ch = curl_init();
 $timeout = 0;
 curl_setopt ($ch, CURLOPT_URL, $url);
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT  6.1)");
 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 $rawdata = curl_exec($ch);
 curl_close($ch);
 $data = explode('"', $rawdata);
 $data = explode(' ', $data['3']);
 $var = $data['0'];
 return round($var,3);
 }

 ?>

bytheway正在免费托管网站0fees.net上测试此代码,所以有任何问题,因为我正在尝试将USD兑换为INR。

2 个答案:

答案 0 :(得分:2)

错误在于以下代码:

function currency($val) {
    $amount = $val;
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amountUSD=?INR";
    // ...                                              ^^^^^^^^^^
}

php尝试评估变量$amountUSD(根据php的string parsing rules)并通知并失败:

PHP Notice:  Undefined variable: amountUSD in usdtoinr.php code on line 3

相反,你应该写:

function currency($val) {
    $amount = floatval($val);
    $url = 'http://www.google.com/ig/calculator?hl=en&q=' . $amount . 'USD=?INR';
    // ...
}

要在将来捕获这些错误,请务必在开发计算机上将error_reporting设置为E_ALL | E_STRICT

此外,谷歌查询的结果是一个JSON文档。由于对象中属性的顺序可能不同,因此必须使用适当的JSON解析器(如json_decode)来解析它,如下所示:

$data = json_decode($rawdata, true);
$tmp = explode(' ', $data['rhs']);
return floatval($tmp[0]);

通常,在用户代理中为您的实际用户代理(例如软件的主页)添加提示也是一个好主意。

答案 1 :(得分:0)

使用此PHP代码

<?php

function currency($from_Currency,$to_Currency,$amount) {
$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 , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode('"', $data['3']);
$var = $data[0];
return round($var,3);
}

?>

并将此输出用于输出,当您输入任何金额时,它将从USD转换为INR

<?php 
 require_once('currency.php');

  $amount=@$_GET["val"];

$from='USD';

$to='INR';

 echo currency($from,$to,$amount);

 ?>

<form method="get" ><input name="val" type="text"><input type="submit" value="Submit"></form>
相关问题