2017-02-09 41 views
0

我正在嘗試使用google翻譯apis將一些英文文本翻譯成荷蘭文。我有以下代碼: -如何從translate.googleapis.com以json格式獲取數據?

$text = urlencode($text); 
$from_lan = 'en'; 
$to_lan = 'nl'; 
$url = "https://translate.googleapis.com/translate_a/single?client=p&sl=".$from_lan."&tl=".$to_lan."&dt=t&q=".$text; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$content = curl_exec($ch); 
print_r($content); 

這我得到的數據: -

[[["uitzicht","view",,,2]],,"en"] 

這不是數組或JSON數據。它是字符串。我怎樣才能得到JSON格式的數據

+0

它不是陣列或JSON數據。它看起來像數組 –

+0

如果輸出是數組,然後使用json_encode()將字符串轉換爲json。 –

+0

數據實際上是帶括號和大括號的字符串。 @Anant – Saswat

回答

0

使用正則表達式去除重複的逗號。然後編碼/解析爲json。這在JS中工作,但未在PHP中測試。

這裏的JS/jquery的版本進行比較:

// error 
$.ajax({ 
    url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=nl&dt=t&q=view", 
    dataType: "text" 
    }) 
    .done(function(data) { 
    console.log(JSON.parse(data)[0][0][0]); 
    }); 

// works (replaces duplicate comma's with single ones) 
$.ajax({ 
    url: "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=nl&dt=t&q=view", 
    dataType: "text" 
    }) 
    .done(function(data) { 
    console.log(JSON.parse(data.replace(/,+/g, ","))[0][0][0]); 
    }); 
0

使用JSON解碼(注意到一個JSON編碼的字符串,並將其轉換成一個PHP變量)

var_dump(json_decode($content)); //Output is object variable 
var_dump(json_decode($content, true)); //Output is array variable 
相關問題