PHP
PHP
Download Photo to a File
See more Facebook Examples
Assuming we have the ID of a Photo, this example demonstrates how to download the photo image data to a file.Chilkat PHP Downloads
<?php
use Chilkat2\Http;
use Chilkat2\JsonObject;
use Chilkat2\OAuth2;
use Chilkat2\Rest;
use Chilkat2\StringBuilder;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example assumes a previously obtained an access token
$oauth2 = new OAuth2();
$oauth2->AccessToken = 'FACEBOOK-ACCESS-TOKEN';
$rest = new Rest();
// Connect to Facebook...
try {
$rest->Connect('graph.facebook.com', 443, true, true);
// Provide the authentication credentials (i.e. the access key)
$rest->SetAuthOAuth2($oauth2);
// Assumes we've already obtained a Photo ID.
$photoId = '10210199026347451';
$sbPath = new StringBuilder();
$sbPath->Append('/v2.7/');
$sbPath->Append($photoId);
// First we're going to get the photo informaton so we can get the URL of the image file data.
// Select the fields we want.
// See https://developers.facebook.com/docs/graph-api/reference/photo/
$rest->AddQueryParam('fields', 'id,album,images');
$responseJson = $rest->FullRequestNoBody('GET', $sbPath->GetAsString());
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$json = new JsonObject();
$json->EmitCompact = false;
$json->Load($responseJson);
// Show the JSON in human-readable format.
echo $json->Emit(), "\n";
// Get the image URL.
$imageUrl = $json->StringOf('images[0].source');
echo 'Downloading from ', $imageUrl, "\n";
$sbImageUrl = new StringBuilder();
$sbImageUrl->Append($imageUrl);
// Build the output local file path.
$sbToPath = new StringBuilder();
$sbToPath->Append('qa_output/fb');
$sbToPath->Append($json->StringOf('id'));
$bCaseSensitive = false;
if ($sbImageUrl->Contains('.jpg', $bCaseSensitive)) {
$sbToPath->Append('.jpg');
} else {
$sbToPath->Append('.png');
}
echo 'Downloading to ', $sbToPath->GetAsString(), "\n";
// Download using Chilkat HTTP.
$http = new Http();
try {
$http->Download($imageUrl, $sbToPath->GetAsString());
echo "Downloaded.\n";
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
}