Google货币转换器返回奇怪的字符串

I'm trying to do a curl request to the google currency converter URL. This part works, and I get back the JSON data however the data appears to be in the wrong encoding. If I try to convert encoding or adjust the values in any way it doesn't work and my json_decode returns NULL.

Do I need to specify encoding or is it related to the keys not having quotes around them?

Here's some code to get a result from them:

    $url = "https://www.google.com/ig/calculator?hl=en&q=" . $amount . $from . "=?" . $to;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $return = curl_exec($ch);
    curl_close($ch);

    var_dump($return);

The result is usually something around this {lhs: "9Â 808.90 U.S. dollars",rhs: "7Â 986.40287 Euros",error: "",icc: true}

I converted the encoding to ISO-8859-1 and it had proper spaces, but it still won't json_decode properly...

Any suggestions?

I never get that weird strings.

test.php

<?php
    $amount = '10$';
    $to = 'EUR';
    $url = "https://www.google.com/ig/calculator?hl=en&q=" . $amount . $from . "=?" . $to;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $return = curl_exec($ch);
    curl_close($ch);

    // dump the output
    var_dump($return);

    /*
    string(59) "{lhs: "10 US$",rhs: "8.14199642 Euros",error: "",icc: true}"
    */

    // quote the unquoted data from Google
    $forJSON = str_replace(array('lhs', 'rhs', 'error', 'icc'), array('"lhs"', '"rhs"', '"error"', '"icc"'), $return);

    // decode the JSON string and turn it into an array
    $toArray = json_decode($forJSON, true);

    // dump the array
    print_r($toArray);

    /* 
    Array
    (
        [lhs] => 9 808.90 U.S. dollars
        [rhs] => 7 986.40287 Euros
        [error] => 
        [icc] => 1
    )
    */
?>

things you should try:

  • make sure you save your file as ANSI - you will get weird values otherwise
  • if above sollution doesn't work, try remaking the file, there must be an encoding somewhere.
  • or maybe you copied 9,808.90 from some program that doesn't actually use , and it's another character there
  • also you should know that Google responds with unquoted data, that is not JSON valid, try to escape like I did and you should be able to decode

You have the values "808.90 U.S. dollars". Just explode() the string and extract the data .

$data = explode('"', $url);
$data = explode(' ', $data['3']);
$var = $data['0'];
return round($var,3);