2017-04-06 54 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