PHP Usage Examples

Learn how to use the HTML to Image API in your PHP applications. These examples show how to convert HTML to images and take screenshots of web pages using PHP.

Installation

First, make sure you have PHP’s cURL extension enabled. You can use Composer to manage your dependencies, but it’s not required for these examples.

HTML to Image Example

This example shows how to convert HTML content to an image using PHP’s cURL:

<?php

function htmlToImage($html, $css = '') {
    $apiKey = 'your-api-key';
    $endpoint = 'https://app.html2img.com/api/html';

    // Prepare the request data
    $data = [
        'html' => $html,
        'css' => $css,
        'width' => 800,
        'height' => 600
    ];

    // Initialize cURL session
    $ch = curl_init($endpoint);

    // Set cURL options
    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)
    ]);

    // Execute the request
    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Check for errors
    if (curl_errno($ch)) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }

    curl_close($ch);

    // Handle the response
    if ($statusCode === 200) {
        // Save the image
        $filename = 'output-' . time() . '.png';
        file_put_contents($filename, $response);
        return $filename;
    } else {
        $error = json_decode($response, true);
        throw new Exception('API Error: ' . ($error['message'] ?? 'Unknown error'));
    }
}

// Example usage
try {
    $html = '
        <div style="padding: 20px; background: #f0f0f0;">
            <h1>Hello, World!</h1>
            <p>This is a test image generated using HTML to Image API.</p>
        </div>
    ';

    $css = '
        h1 { color: #2563eb; }
        p { color: #4b5563; }
    ';

    $filename = htmlToImage($html, $css);
    echo "Image saved as: " . $filename;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Screenshot API Example

This example demonstrates how to take a screenshot of a webpage:

<?php

function takeScreenshot($url, $options = []) {
    $apiKey = 'your-api-key';
    $endpoint = 'https://app.html2img.com/api/screenshot';

    // Merge default options with provided options
    $defaultOptions = [
        'width' => 1920,
        'height' => 1080,
        'dpi' => 1,
        'fullpage' => true
    ];
    
    $options = array_merge($defaultOptions, $options);
    
    // Prepare the request data
    $data = array_merge(['url' => $url], $options);

    // Initialize cURL session
    $ch = curl_init($endpoint);

    // Set cURL options
    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)
    ]);

    // Execute the request
    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Check for errors
    if (curl_errno($ch)) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }

    curl_close($ch);

    // Handle the response
    if ($statusCode === 200) {
        // Save the screenshot
        $filename = 'screenshot-' . time() . '.png';
        file_put_contents($filename, $response);
        return $filename;
    } else {
        $error = json_decode($response, true);
        throw new Exception('API Error: ' . ($error['message'] ?? 'Unknown error'));
    }
}

// Example usage
try {
    $options = [
        'width' => 1200,
        'height' => 800,
        'fullpage' => true,
        'dpi' => 2 // For high-resolution screenshots
    ];

    $filename = takeScreenshot('https://example.com', $options);
    echo "Screenshot saved as: " . $filename;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Advanced Usage

Handling Timeouts

For large pages or complex HTML, you might need to increase the timeout:

// Set a longer timeout (30 seconds)
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

Error Handling

Here’s a more detailed error handling example:

function handleApiError($response, $statusCode) {
    $error = json_decode($response, true);
    
    switch ($statusCode) {
        case 401:
            throw new Exception('Unauthorized: Invalid API key');
        case 402:
            throw new Exception('Payment Required: Please check your subscription');
        case 429:
            throw new Exception('Too Many Requests: Rate limit exceeded');
        default:
            throw new Exception('API Error: ' . ($error['message'] ?? 'Unknown error'));
    }
}

Saving with Custom Filenames

You can customize the output filename based on your needs:

function generateFilename($prefix = 'image', $extension = 'png') {
    $timestamp = time();
    $random = substr(md5(uniqid()), 0, 6);
    return sprintf('%s-%s-%s.%s', $prefix, $timestamp, $random, $extension);
}

$filename = generateFilename('my-screenshot');

Remember to replace ‘your-api-key’ with your actual API key and handle the API key securely using environment variables.

Best Practices

  1. API Key Security
    • Store your API key in environment variables
    • Never commit API keys to version control
    • Use different API keys for development and production
$apiKey = getenv('HTML2IMG_API_KEY') ?: die('API key not found');
  1. Error Handling

    • Always implement proper error handling
    • Log errors for debugging
    • Provide meaningful error messages to users
  2. Resource Management

    • Clean up temporary files after processing
    • Close cURL handles properly
    • Implement proper timeout handling
  3. Performance

    • Cache results when possible
    • Use appropriate image dimensions
    • Optimize HTML/CSS before conversion

The examples above are for demonstration purposes. In a production environment, you should implement proper error handling, logging, and security measures.