2012-08-10 118 views
1

我想要對谷歌貨幣轉換器URL做一個curl請求。這部分工作,我找回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正確...

有什麼建議嗎?

回答

1

我從來沒有得到那種奇怪的字符串。

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 
    ) 
    */ 
?> 

事情你應該嘗試:

  • 確保您將文件保存爲ANSI - 你會得到怪異的值,否則
  • 如果上述sollution不起作用,嘗試重新創建文件,必須有某個編碼。
  • 或者你從一些程序實際上並未使用,複製9,808.90,它的另一個字符有
  • 你也應該知道,谷歌與未加引號的數據來響應,這不是JSON有效,試圖逃跑像我一樣和你應該能夠解碼
0

您的值爲「808.90美元」。只需爆炸()字符串並提取數據。

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

不幸的是,如果rhs超過1000這種方法不起作用。我最終使用了str_replace和preg_match的組合來獲取我想要的值。 – 2012-08-14 15:17:44