背景:
我创建了一个显示不同国家/地区货币汇率的网站。我使用 Google 的货币转换器 API 来执行计算。
http://www.google.com/ig/calculator?h1=en&q=9999gbp=?usd
注意我传入的查询,例如9999 英镑
为 美元
。
API 返回:
{lhs: "9999 英镑",rhs: "15 769.4229 美元",error: "",icc: true}
Google 在 5
和 7
之间用空格分隔了 15 769.4229
。
当我在我的网站上返回计算结果时,这会导致出现问题,因为空白字符被替换为 � 符号。
请看下面的屏幕截图:
知道这个符号叫什么以便我可以尝试将其删除吗?
<?php
// Check to ensure that form has been submitted
if (isset($_POST['amount'], $_POST['from'], $_POST['to'])) {
$amount = trim($_POST['amount']);
$from = $_POST['from'];
$to = $_POST['to'];
try {
$conversion = currency_convert($googleCurrencyApi, $amount, $from, $to);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage();
}
// Check URL has been formed
if ($conversion == false) {
echo 'Sorry, something went wrong';
} else {
echo $conversion[0], ' = ', $conversion[1];
}
}
function currency_convert($googleCurrencyApi, $amount, $from, $to) {
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$expl = explode('"', $result);
if ($expl[1] == '' || $expl[3] == '') {
throw new Exception('An error has occured. Unable to get file contents');
} else {
return array(
$expl[1],
$expl[3]
);
}
}
?>
到目前为止,这是我的代码,因此您可以理解我的逻辑背后的想法。
最佳答案
这很可能是不间断空格,尝试替换成空格:
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$result = str_replace("\xA0", " ", $result);
关于php - � 从 Google 货币 API 返回的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9234437/