2013-03-24 87 views
1

我嘗試使用谷歌翻譯API這個頁面上所顯示的一個節點...選擇JSON字符串

https://developers.google.com/translate/v2/using_rest

當我代替我的API密鑰,它工作正常,並顯示翻譯的文本如下所示。

GET https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world

{ 
    "data": { 
     "translations": [ 
      { 
       "translatedText": "Hallo Welt", 
       "detectedSourceLanguage": "en" 
      } 
     ] 
    } 
} 

我會想返回只使用PHP文本,即 「喂世界報」。

我使用了json_decode函數,但它返回所有內容。

+0

什麼是您的PHP代碼? – 2013-03-24 06:20:00

回答

4
$url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&target=de&q=Hello%20world"; 
$data = file_get_contents($url); 
$json = json_decode($data); 

echo $json->data->translations[0]->translatedText; 
+0

這不會返回任何東西。但是print_r($ json-> data-> translations);返回Array([0] => stdClass Object([translatedText] => Hallo [detectedSourceLanguage] => en)) – shantanuo 2013-03-24 06:55:45

+0

編輯答案,translations是一個數組。 – flux 2013-03-24 07:10:25

0
$object = json_decode($yourJSONString); 
echo $object->data->translations->translatedText; 

一旦你使用json_decode(),你只需要使用生成的對象,但是你使用任何其他PHP對象。