通过使用PHP中的参数调用URL来获取JSON对象

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了通过使用PHP中的参数调用URL来获取JSON对象脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想通过调用moodle url来获取json数据:
https://<;moodledomain>/login/token.PHP?username=test1&amp;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'

任何人都可以建议我吗?

json_decode()需要一个字符串,而不是一个URL.您正在尝试解码该url(并且json_decode()不会执行http请求来为您获取url的内容).

你必须自己获取json数据:

$JSON = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

脚本宝典总结

以上是脚本宝典为你收集整理的通过使用PHP中的参数调用URL来获取JSON对象全部内容,希望文章能够帮你解决通过使用PHP中的参数调用URL来获取JSON对象所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。