TRiBByX
11/14/2016 - 12:04 PM

REST PHP

REST PHP

<?php

#GET
if (is_callable(curl_init)) echo 'Curl enabled';
else echo 'Curl is not enabled.';

$curl = curl_init();

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_URL, 'http://jsonplaceholder.typicode.com/posts/8');

$result = curl_exec($curl);

curl_close($curl);

echo '<pre>';
print_r($result);
echo '</pre>';

$jsonObj = json_decode($result);
echo $jsonObj -> title;


#POST
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://jsonplaceholder.typicode.com/posts');
curl_setopt($curl, CURLOPT_POST, true);
$data = array('userId' => 1, 'title' => "This is a REST post!", 'body' => 'This is the body');
$jsonData = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$postResult = curl_exec($curl);

echo '<hr/>';
echo 'result of my POST request: ';
print_r($postResult);