2017-04-06 58 views
0

如何使用PHP讀取JSON數據響應?閱讀JSON數據帶有PHP令牌

這是代碼:

$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.", 
    array(
    "X-Mashape-Key" => "MY X-Mashape-Key", 
    "Accept" => "application/json" 
) 
); 

,並給我這個JSON數據:

{ 
    "original": "This sentnce has some probblems.", 
    "suggestion": "This sentence has some problems.", 
    and ... 
} 

我想在URL返回 「suggestion」 與$

這是一個例子:

$user_id = '123456789' 
$mytext = '?' // I WANT RETURN "suggestion" HERE ! 

$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext 
file_get_contents($url); 
+0

給我們輸入和預期輸出的一個例子。 – Dimi

回答

0

您可以使用json_decode()。

參見: http://php.net/manual/en/function.json-decode.php

你只需要做:

$response = json_decode($response,1); 
echo $response['suggestion']; 

設置json_decode的)到1(真)的第二個參數(將返回JSON數據的關聯數組。

如果你想用你的代碼示例,包括它的URL:

$user_id = '123456789' 
$json = json_decode($response,1); 
$mytext = $json['suggestion']; 

$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext 
file_get_contents($url); 
+0

謝謝,但我想在$ url中使用$ – Nomad

+0

返回它謝謝工作! – Nomad

0

使用json_decode將json_response轉換爲array.Add第二個參數'true'使其成爲您應該熟悉的數組。

通過指定訪問建議變量。

$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.", 
    array(
    "X-Mashape-Key" => "MY X-Mashape-Key", 
    "Accept" => "application/json" 
) 
); 
$data=json_decode($response,true); 
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion']; 
echo $url; 
+0

謝謝你的回答我怎樣才能返回它在一個URL $ – Nomad

+0

我補充的例子。再次感謝 – Nomad