我正在尝试对谷歌货币转换器网址发出卷曲请求。这部分有效,我取回了 JSON 数据,但数据似乎编码错误。如果我尝试以任何方式转换编码或调整值,它不起作用,我的json_decode返回 NULL。
我是否需要指定编码,或者它是否与键周围没有引号有关?
下面是一些从它们获取结果的代码:
$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);
结果通常是围绕这个{lhs: "9Â 808.90 U.S. dollars",rhs: "7Â 986.40287 Euros",error: "",icc: true}
我将编码转换为 ISO-8859-1,它有适当的空格,但它仍然无法正常json_decode......
有什么建议吗?
我从来没有得到过那么奇怪的字符串。
测试.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
)
*/
?>
您应该尝试的事情:
- 确保将文件另存为 ANSI - 否则你会得到奇怪的值
- 如果上述解析不起作用,请尝试重新制作文件,某处必须有编码。
- 或者,也许您从某个实际上不使用
,
的程序复制了 9,808.90,并且它是那里的另一个字符 - 您还应该知道Google使用未引用的数据进行响应,这是无效的JSON,请尝试像我一样进行逃逸,您应该能够解码
您的值为"808.90 美元"。只需分解()字符串并提取数据。
$data = explode('"', $url);
$data = explode(' ', $data['3']);
$var = $data['0'];
return round($var,3);