Appearance
PHP Examples
Integration examples for PHP applications.
Basic Example
php
<?php
function generateOGImage($title, $subtitle = '', $theme = 'dark') {
$apiKey = getenv('OG_IMAGE_API_KEY');
$data = [
'title' => $title,
'subtitle' => $subtitle,
'theme' => $theme
];
$ch = curl_init('https://ogimageapi.io/api/generate');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-API-Key: ' . $apiKey
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
$error = json_decode($response, true);
throw new Exception($error['message'] ?? 'Unknown error');
}
return $response;
}
// Usage
try {
$imageData = generateOGImage(
'Hello from PHP',
'A simple example'
);
file_put_contents('og-image.png', $imageData);
echo "Image saved!";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}Full-Featured Client Class
php
<?php
class OGImageClient {
private string $apiKey;
private string $baseUrl = 'https://ogimageapi.io';
public function __construct(?string $apiKey = null) {
$this->apiKey = $apiKey ?? getenv('OG_IMAGE_API_KEY');
if (empty($this->apiKey)) {
throw new InvalidArgumentException('API key is required');
}
}
public function generate(array $options): string {
$data = [
'title' => $options['title'] ?? '',
'subtitle' => $options['subtitle'] ?? '',
'author_name' => $options['author_name'] ?? '',
'author_avatar_url' => $options['author_avatar_url'] ?? '',
'theme' => $options['theme'] ?? 'dark',
'template' => $options['template'] ?? 'default'
];
return $this->request('POST', '/api/generate', $data, true);
}
public function getUsage(): array {
$response = $this->request('GET', '/api/user/usage');
return json_decode($response, true);
}
private function request(
string $method,
string $endpoint,
?array $data = null,
bool $binary = false
): string {
$ch = curl_init($this->baseUrl . $endpoint);
$headers = [
'X-API-Key: ' . $this->apiKey
];
if ($method === 'POST' && $data) {
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
$error = json_decode($response, true);
throw new Exception($error['message'] ?? 'Request failed');
}
return $response;
}
}
// Usage
$client = new OGImageClient();
// Generate image
$imageData = $client->generate([
'title' => 'PHP Integration Guide',
'subtitle' => 'Step-by-step tutorial',
'theme' => 'dark',
'template' => 'vibrant'
]);
file_put_contents('guide.png', $imageData);
// Check usage
$usage = $client->getUsage();
echo "Used {$usage['used']}/{$usage['quota']} ({$usage['percent_used']}%)";Laravel Integration
php
<?php
// app/Services/OGImageService.php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class OGImageService {
private string $apiKey;
private string $baseUrl = 'https://ogimageapi.io';
public function __construct() {
$this->apiKey = config('services.ogimage.key');
}
public function generate(array $options): string {
$response = Http::withHeaders([
'X-API-Key' => $this->apiKey
])->post($this->baseUrl . '/api/generate', [
'title' => $options['title'] ?? '',
'subtitle' => $options['subtitle'] ?? '',
'author_name' => $options['author_name'] ?? '',
'theme' => $options['theme'] ?? 'dark',
'template' => $options['template'] ?? 'default'
]);
if (!$response->successful()) {
throw new \Exception($response->json('message', 'Unknown error'));
}
return $response->body();
}
}
// app/Http/Controllers/OGImageController.php
namespace App\Http\Controllers;
use App\Services\OGImageService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class OGImageController extends Controller {
public function generate(Request $request, OGImageService $service) {
$validated = $request->validate([
'title' => 'required|string|max:200',
'subtitle' => 'nullable|string|max:300',
'theme' => 'nullable|in:dark,light'
]);
try {
$imageData = $service->generate($validated);
return response($imageData)
->header('Content-Type', 'image/png')
->header('Cache-Control', 'public, max-age=86400');
} catch (\Exception $e) {
return response()->json([
'error' => $e->getMessage()
], 500);
}
}
}
// routes/web.php
Route::get('/og', [OGImageController::class, 'generate']);Configuration:
php
// config/services.php
return [
// ... other services
'ogimage' => [
'key' => env('OG_IMAGE_API_KEY'),
],
];WordPress Integration
php
<?php
/**
* Plugin Name: OG Image Generator
* Description: Generate Open Graph images automatically
*/
class OG_Image_Generator {
private $api_key;
public function __construct() {
$this->api_key = get_option('og_image_api_key');
add_action('save_post', [$this, 'generate_og_image'], 10, 2);
add_filter('og_image_url', [$this, 'get_og_image_url'], 10, 2);
}
public function generate_og_image($post_id, $post) {
if ($post->post_status !== 'publish') {
return;
}
$image_data = $this->call_api([
'title' => $post->post_title,
'subtitle' => get_the_excerpt($post),
'author_name' => get_the_author_meta('display_name', $post->post_author),
'theme' => 'dark'
]);
if ($image_data) {
$upload_dir = wp_upload_dir();
$filename = 'og-' . $post_id . '.png';
$filepath = $upload_dir['path'] . '/' . $filename;
file_put_contents($filepath, $image_data);
update_post_meta($post_id, '_og_image_path', $filepath);
update_post_meta($post_id, '_og_image_url', $upload_dir['url'] . '/' . $filename);
}
}
private function call_api($data) {
$response = wp_remote_post('https://ogimageapi.io/api/generate', [
'headers' => [
'Content-Type' => 'application/json',
'X-API-Key' => $this->api_key
],
'body' => json_encode($data),
'timeout' => 30
]);
if (is_wp_error($response)) {
return false;
}
$code = wp_remote_retrieve_response_code($response);
if ($code !== 200) {
return false;
}
return wp_remote_retrieve_body($response);
}
public function get_og_image_url($url, $post_id) {
$og_url = get_post_meta($post_id, '_og_image_url', true);
return $og_url ?: $url;
}
}
new OG_Image_Generator();