2014-09-06 281 views
0

嘗試構建基於IP的自動貨幣轉換。搜索JSON結果

我可以得到2位數的國家代碼很容易..

$remote_IP_url = 'http://ip-api.com/json/' . $_SERVER['REMOTE_ADDR']; 
$remote_user_data = json_decode(file_get_contents($remote_IP_url)); 
if ($remote_user_data->status == 'success') { 
$user_country = $remote_user_data->countryCode; 
// do your check and get the currency code w.r.t. the $user_country in the previous line 
echo $user_country; 

但我需要將其轉換爲3位爲谷歌工作。

$ch = curl_init(); 
    // 2. set the options, including the url 
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com/finance/converter?      a=".$price."&from=USD&to=".$convertto." "); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    // 3. execute and fetch the resulting HTML output 
    $output = curl_exec($ch); 
    // 4. free up the curl handle 
    curl_close($ch); 
    $data = explode('<div id=currency_converter_result>',$output); 
    $data2 = explode('<div id=currency_converter_result>',$data['1']); 
    $data3=explode('<span>',$data2['0']); 
    $data4=explode('</span>',$data3['1']); 
    $data5=explode(' ',$data4['0']); 
    return $data5[0]; 

我已經找到了國家代碼貨幣代碼的源在http://country.io/currency.json這給結果作爲..

{ 
     "BD": "BDT", 
     "BE": "EUR", 
     "BF": "XOF", 
     "BG": "BGN", 
     "BA": "BAM", 
     "BB": "BBD", 
     "WF": "XPF", 
     "BL": "EUR", 
     "BM": "BMD", 
     "BN": "BND", 
     "BO": "BOB", 

...

但我不知道是怎麼在JSON中搜索所需的國家代碼並從中選擇貨幣代碼。

回答

0

假設你$user_country變量不包含國家代碼,你可以從country.io獲取JSON,將其轉換爲一個數組,並檢查國家代碼密鑰存在於該數組中。

將JSON從country.io轉換爲數組並將其放入PHP文件中可能不是一個好主意,而是將其放入PHP文件中,而不是在每次請求時將其取出並轉換爲數組。

<?php 
$currency = json_decode(file_get_contents('http://country.io/currency.json'), true); 

if(isset($currency[ $user_country ])) 
{ 
    $currency_code = $currency[ $user_country ]; 
} 
else 
{ 
    $currency_code = 'Not found'; 
} 

echo $currency_code; 
0

假設你使用PHP 5.4:

$code = "BB"; 
$jsonString = '{"BB":"BBD","WF":"XPF"}'; 

$longCode = json_decode($jsonString, true)[$code]; 

// $longCode == "BBD"