私はmoodle urlを呼び出してjsonデータを取得しようとしています:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
moodleシステムのレスポンスformatは次のようになります:
{"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!";
}
結果は次のとおりですndefined
ここで質問: json応答をどのように処理できますかformat moodleシステムの?どんなアイデアでもいいです。
[UPDATE]:curlを介して別のアプローチを使用し、php.iniで次の行を変更しました:* extension = php_openssl.dll *、* allow_url_include = On *ですが、エラーが発生しています:Notice:非オブジェクトのプロパティを取得しようとしています。更新されたコードは次のとおりです。
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()は[〜#〜] not [〜#〜] URLのコンテンツを取得するためにhttpリクエストを実行します)。
Jsonデータを自分でフェッチする必要があります。
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};