我试图通过调用moodle url来获取json数据:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
moodle系统的响应格式是这样的:
{"token":"a2063623aa3244a19101e28644ad3004"}
我尝试用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响应格式?任何想法都会很棒。
[UPDATE]: 我通过 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'
有人可以告诉我吗?
答案 0 :(得分:30)
json_decode()需要一个字符串,而不是一个URL。您正在尝试解码该网址(并且json_decode()将不执行http请求以获取您的网址内容。)
您必须自己获取json数据:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};