Skip to content

MoodleRest examples

Lawrence Lagerlof edited this page Oct 9, 2018 · 1 revision

Below you can find more usage examples.

<?php

require_once "MoodleRest.php";

// Set this variables accordingly

$ip = '127.0.0.1';
$moodle_folder = 'moodle';
$token = '8f12e614dae30735260a045313caa400';


// Uncomment the example block you want to run. The first block (example A) is already uncommented.

// Example A: Two requests using the same object, returns array

$MoodleRest = new MoodleRest();
$MoodleRest->setServerAddress("http://$ip/$moodle_folder/webservice/rest/server.php");
$MoodleRest->setToken($token);
$MoodleRest->setReturnFormat(MoodleRest::RETURN_ARRAY);

$result1 = $MoodleRest->request('core_group_get_groups', array('groupids' => array(1,2))); // groupids[0]=1&groupids[1]=2

echo "result1:\n" . print_r($result1, true);
$params = array('userlist' => array(array('userid' => 5, 'courseid' => 2), array('userid' => 4, 'courseid' => 2))); //userlist[0][userid]=5&userlist[1][userid]=4&userlist[0][courseid]=2&userlist[1][courseid]=2

$result2 = $MoodleRest->request('core_user_get_course_user_profiles', $params);

echo "result2:\n" . print_r($result2, true);
die();


// Example B: Returning and printing a json
/*
$MoodleRest = new MoodleRest();
$MoodleRest->setServerAddress("http://$ip/$moodle_folder/webservice/rest/server.php");
$MoodleRest->setToken($token);
$MoodleRest->setReturnFormat(MoodleRest::RETURN_JSON);

$json = $MoodleRest->request('core_group_get_groups', array('groupids' => array(1,2)));

$MoodleRest->printRequest(); // this prints the header and the json string
//echo $json; // this prints only the json string
die();
*/


// Example C: Returning a xml using method chaining
/*
$xml =
    (new MoodleRest())->setServerAddress("http://$ip/$moodle_folder/webservice/rest/server.php")->
    setToken($token)->
    setReturnFormat(MoodleRest::RETURN_XML)->request('core_group_get_groups', array('groupids' => array(1,2)));

echo $xml;
die();
*/
Clone this wiki locally