Batch
requests can help, you POST
your GET
queries to /?batch
endpoint (as encoded JSON
), the response will return as:
,
each array contains a GET
query you requests you can access data using $batch[{index}]['body']['{desired_field}']
<?php
$access_token = '{app_id}|{app_secret}'; // a valid user or an app access_token
$queries = array(
array('method' => 'GET', 'relative_url' => '/google?fields=about,name'),
array('method' => 'GET', 'relative_url' => '/fiverras3t5wv4tbsdf?fields=about,name'), // this page doesn't exist for sure
array('method' => 'GET', 'relative_url' => '/designtaxi?fields=about,name'),
array('method' => 'GET', 'relative_url' => '/smashmag?fields=about,name'),
array('method' => 'GET', 'relative_url' => '/XstackoverflowX?fields=about,name'), // this page doesn't exist for sure
array('method' => 'GET', 'relative_url' => '/asd121233?fields=about,name'), // this page doesn't exist for sure
);
$p = array('access_token' => $access_token);
$batch = api('/?batch='.json_encode($queries), 'POST', $p);
foreach ($batch as $response) { // loop check each inner response
if ($response['code'] == '200') { // if the graph has returned data
$response = json_decode($response['body'], true);
print '<p>About '. $response['name'].': ' . $response['about'].'</p>'.PHP_EOL;
} else { // the pages doesn't exists (404 bad request)
print '<p>The page doesn\'t exists'.'</p>'.PHP_EOL;
}
}
function api( $path, $method = NULL, $params = NULL) {
$apiCall = 'https://graph.facebook.com/v2.0' . $path;
// Initiate the cURL extension
$ch = curl_init();
// Check if the method is GET or POST
if ( is_null($method) ) {
curl_setopt( $ch, CURLOPT_POST, false );
if ( is_null($params) ) {
// NO PARAMS
} else {
$apiCall .= '?' . http_build_query($params);
// echo 'NULL:'.$apiCall;
}
} else if ( $method === 'GET' ) {
curl_setopt( $ch, CURLOPT_POST, false );
if ( is_null($params) ) {
// NO PARAMS
} else {
$apiCall .= '?' . http_build_query($params);
// echo 'GET: '.$apiCall;
}
} else if ( $method === 'POST' ) {
curl_setopt( $ch, CURLOPT_POST, true );
// Check if any params are set
if ( is_null($params) ) {
// NO PARAMS
} else {
$params = http_build_query($params);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
}
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
// Execute cURL
$apiResults = curl_exec($ch);
// Close cURL
curl_close($ch);
// return an JSON *ARRAY* not an object
return json_decode($apiResults, true);
}
php-ref