通过在 PHP 中调用带参数的 URL 来获取 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14262732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting JSON Object by calling a URL with parameters in PHP
提问by Dozent
I'm trying to get json data by calling moodle url:
我试图通过调用moodle url来获取json数据:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response formatof moodle system is like this:
Moodle系统的响应格式是这样的:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
我尝试用 PHP 处理的结果:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
结果是:未定义
Now the question:How can I process the json response formatof moodle system? Any idea would be great.
现在的问题是:如何处理moodle系统的json响应格式?任何想法都会很棒。
[UPDATE]:I have used another approach via curland changed in php.inifollowing lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice:Trying to get property of non-object. Here is the updated code:
[更新]:我通过curl使用了另一种方法,并在php.ini 中更改了以下几行:*extension=php_openssl.dll*, *allow_url_include = On*,但现在出现错误:注意:尝试获取非属性目的。这是更新后的代码:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
任何人都可以给我建议吗?
回答by Marc B
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOTdo an http request to fetch the url's contents for you).
json_decode() 需要一个字符串,而不是一个 URL。您正在尝试对该 url 进行解码(并且 json_decode()不会执行 http 请求来为您获取 url 的内容)。
You have to fetch the json data yourself:
您必须自己获取 json 数据:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

