curl is an extension that will have to be installed/working on your hosting environment to be available. If it is then PHP comes with quite a few functions (library) to be able to use curl to connect and communicate with other servers.
You can read more here: http://www.php.net/manual/en/intro.curl.php
I would probably change my code to move the type variable into the construct instead of sending it in with each call
restCall.php
[php]<?php
class restCall {
private $url;
private $port;
private $type;
public function __construct($url = ‘’, $port = 80, $type = ‘json’) {
if (!function_exists(‘curl_init’)) {
throw new Exception(‘Sorry cURL is not installed!’);
}
$this->url = $url;
$this->port = $port;
$this->type = $type;
}
public function call($call = ‘’) {
$return = false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url . $call);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
if (!$response) {
throw new Exception('Error while calling api');
}
switch ($this->type) {
case 'json':
$return = json_decode($response);
break;
case 'xml':
$return = simplexml_load_string($response);
break;
default:
throw new Exception('API calls of this type is not implemented');
break;
}
return $return;
}
public function setUrl($url = ‘’) {
$this->url = $url;
}
public function setPort($port = 80) {
$this->port = $port;
}
}[/php]
demo.php
[php]<?php
try {
require_once ‘restCall.php’;
$jsonTest = new restCall(‘https://graph.facebook.com/’);
$response = $jsonTest->call(4);
$anotherUser = $jsonTest->call(5);
/*
* Or we could get multiple
*/
$users = array();
$userIds = array(7,10,11,13,27,28,29);
foreach ($userIds as $userId) {
$users[] = $jsonTest->call($userId);
}
?>
First fetch
Another user
Userlist
<?php foreach ($users as $user) { ?>
- Name: <?= $user->name ?>
- Link: <?= $user->link ?>
<?php } ?>
<?php
/*
* You can continue to make calls here as well
*/
$user3 = $jsonTest->call(‘jimleirvik’); //etc…
} catch (Exception $e) {
echo 'Error: ’ . $e->getMessage();
}
[/php]
Output:
[code]First fetch
Name: Mark Zuckerberg
Link: http://www.facebook.com/zuck
Another user
Name: Chris Hughes
Link: http://www.facebook.com/ChrisHughes
Userlist
Name: Arie Hasit
Link: http://www.facebook.com/arie.hasit
Name: Marcel Laverdet
Link: http://www.facebook.com/marcel
Name: Soleio
Link: http://www.facebook.com/soleio
Name: Chris Putnam
Link: http://www.facebook.com/putnam
Name: Colin Kelly
Link: http://www.facebook.com/improvite
Name: Mark Kaganovich
Link: http://www.facebook.com/kaganovich
Name: Andrei Boros
Link: http://www.facebook.com/andrei.boros.3
[/code]