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:
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.
This is most probably non-breaking space, try replacing into space:
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$result = str_replace("\xA0", " ", $result);
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
(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("�", "", $result );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With