Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

� char returned from Google currency API

Tags:

php

google-api

Background:

I've created a website that displays currency rates from various countries. I use Google's currency converter API to perform the calculations.

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

Notice the query I have passed in e.g. 9999 Great British Pounds to United States Dollars.

The API returns:

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

Google has separated the 15 769.4229 with white space between the 5 and the 7.

This causes a problem when I return the results of a calculation on my site as the white space char is replaced with the � symbol.

See screen shot below:

enter image description here

Any ideas what this symbol is called so I can attempt to remove it?

<?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]
        );
    }
}
?>

Here's my code so far at the moment, so you get the idea behind my logic.

like image 421
keenProgrammer Avatar asked Feb 10 '12 20:02

keenProgrammer


2 Answers

This is most probably non-breaking space, try replacing into space:

$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$result = str_replace("\xA0", " ", $result);
like image 151
dev-null-dweller Avatar answered Nov 07 '22 05:11

dev-null-dweller


Try modifying your code so that you're UTF8 decoding the data that's being returned from Google:

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

I'm presuming that your default encoding is ISO-8859-1

EDIT

(As per comments) The issue may be that you have been sent a null character. Try this:

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

or

$result = str_replace("&#x0;", "", $result );
like image 40
Ben D Avatar answered Nov 07 '22 03:11

Ben D