无法使用PHP获取JSON数据

时间:2015-12-25 15:24:40

标签: php json

这是我的PHP代码:(文件名是getname.php)

<?php
$query = $_GET['p']; //supplied as getname.php?p=easy+is+his+name

$link = 'http://api.genius.com/search?access_token=MY_ACCESS_TOKEN&q='.$query;
$json = file_get_contents($link);
$obj = json_decode($json);

echo $obj->response->hits[0]->result->title;
?>

当我运行此代码时,错误就像,

  

file_get_contents(http://api.genius.com/search?access_token=MY_ACCESS_TOKEN&q=easy是他的名字):无法打开流:HTTP请求失败!不支持HTTP / 1.1 505 HTTP版本 - 第5行

当我把代码写成时,

<?php
$link = 'http://api.genius.com/search?access_token=MY_ACCESS_TOKEN&q=easy+is+his+name';
$json = file_get_contents($link);
$obj = json_decode($json);

echo $obj->response->hits[0]->result->title;
?>

,显示预期结果。为什么会这样?

1 个答案:

答案 0 :(得分:0)

修正:

<?php
$query = $_GET['p']; //supplied as getname.php?p=easy+is+his+name

$link = 'http://api.genius.com/search?access_token=MY_ACCESS_TOKEN&q='.urlencode($query);
$json = file_get_contents($link);
$obj = json_decode($json);

echo $obj->response->hits[0]->result->title;
?>