我正在使用PHP和Google财经开发货币转换器作为我的系统设计类的一部分。
你能帮我解决一下错误:
“注意:未定义的偏移:1”?
以下是代码:
HTML
<form action="" method="POST">
Amount:
<input type="text" name="amount" /><br/><br/>
From:
<input type="text" name="from" /><br/><br/>
To:
<input type="text" name="to" /><br/><br/>
<input type="submit" id="convert" name="convert"/>
</form>
PHP
<?php
function currency_convert($amount, $from, $to){
$url='https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to;
$data = file_get_contents($url);
preg_match("/<span class=bld>(.*)<\/span>/",$data,$converted);
echo $converted[1];
}
if(isset($_POST['convert'])){
$amount=$_POST['amount'];
$from=$_POST['from'];
$to=$_POST['to'];
currency_convert($amount, '$from', '$to');
}
?>
答案 0 :(得分:1)
享受! )
<?php
function currency_convert($amount, $from, $to){
$url = 'https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from . '&to=' . $to;
$data = @file_get_contents($url);
if (!$data) {
return null;
}
if (!preg_match("/<span class=bld>(.*)<\/span>/", $data, $converted)) {
return null;
}
$converted = explode(' ', $converted[1], 2);
return (float)$converted[0];
}
if(isset($_POST['convert'])){
$convertedAmount = currency_convert($_POST['amount'], $_POST['from'], $_POST['to']);
echo $_POST['amount'] . ' ' . $_POST['from'] . ' = ' . number_format($convertedAmount, 2, '.', ' ') . ' ' . $_POST['to'] . "\n";
}
<强>说明:强>
'$to'
不等于$to
,因为'strings in quotes'
不由PHP引擎解析,仅在"double quotes"
中。这就是您的请求错误并且file_get_contents
收到另一个有错误的文档的原因。因此,preg_match
返回false,$converted
是一个空数组。这就是为什么试图让$converted[1]
通知。