【问题标题】:� char returned from Google currency API� 从 Google 货币 API 返回的字符
【发布时间】:2012-02-10 20:34:24
【问题描述】:

背景:

我创建了一个显示不同国家货币汇率的网站。我使用 Google 的货币转换器 API 来执行计算。

http://www.google.com/ig/calculator?h1=en&q=9999gbp=?usd

请注意我传入的查询,例如9999 Great British PoundsUnited States Dollars

API 返回:

{lhs: "9999 British pounds",rhs: "15 769.4229 U.S. dollars",error: "",icc: true}

Google 在57 之间用空格分隔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]
        );
    }
}
?>

这是我目前的代码,所以你明白我的逻辑背后的想法。

【问题讨论】:

  • 我猜问题只是编码。你试过utf8_decode ( string $data )吗?
  • $result = $conversion[0] . $conversion[1]; echo utf8_decode($result); 仍然返回提到的字符

标签: php google-api


【解决方案1】:

这很可能是不间断空格,请尝试替换为空格:

$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$result = str_replace("\xA0", " ", $result);

【讨论】:

    【解决方案2】:

    尝试修改您的代码,以便对从 Google 返回的数据进行 UTF8 解码:

    // Check URL has been formed 
        if ($conversion == false) {
            echo 'Sorry, something went wrong';
        } else {
            echo utf8_decode($conversion[0]), ' = ', utf8_decode($conversion[1]);
        }
    

    我假设您的默认编码是 ISO-8859-1

    编辑

    (根据 cmets)问题可能是您收到了一个空字符。试试这个:

    $result = str_replace("\0", "", $result );
    

    $result = str_replace("&#x0;", "", $result );
    

    【讨论】:

    • 仍然返回相同的内容。这个 utf8_decode 可能会被覆盖吗?
    • @keenProgrammer 添加了一个额外的方法
    【解决方案3】:

    str_replace之后做:

    $result_amt = utf8_decode($amount);
    

    您将获得? 字符而不是空格。所以然后再使用str_replace 删除? 字符:

    $result =str_replace("?","", $result_amt );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 2015-10-06
      • 2014-12-07
      • 1970-01-01
      • 2017-04-05
      • 2023-04-01
      相关资源
      最近更新 更多