通过在PHP中使用参数调用URL来获取JSON对象 [英] Getting JSON Object by calling a URL with parameters in PHP
问题描述
我正在尝试通过调用moodle url获取json数据:
I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
情感系统的响应格式是这样的:
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
我尝试使用PHP处理的结果:
The result I tried to process with 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!";
}
结果是:未定义
现在的问题: 我该如何处理Moodle系统的json响应 format ?任何想法都很棒.
Now the question: How can I process the json response format of moodle system? Any idea would be great.
[更新]: 我通过 curl 使用了另一种方法,并在 php.ini 中更改了以下几行:* extension = php_openssl.dll *,* allow_url_include = On *,但是现在出现错误:注意::试图获取非对象的属性.这是更新的代码:
[UPDATE]: I have used another approach via curl and changed in php.ini following 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:
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'
有人可以建议我吗?
推荐答案
json_decode()需要一个字符串,而不是URL.您正在尝试对该网址进行解码(并且json_decode()将不发出http请求以为您获取该网址的内容).
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
您必须自己获取json数据:
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};
这篇关于通过在PHP中使用参数调用URL来获取JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!