Skip to Content
Code ExamplesPHP Example

PHP Example

This example demonstrates how to use the WebClassifAI API with PHP using the built-in curl extension.

Basic Example

<?php class WebClassifAI { private const API_ENDPOINT = 'https://api.classifai.com/v1'; public static function classifyUrls(array $urls, string $apiKey, string $taxonomy = 'iab-1.0'): array { $payload = [ 'urls' => $urls, 'api_key' => $apiKey, 'taxonomy' => $taxonomy ]; $ch = curl_init(self::API_ENDPOINT); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($payload), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json' ] ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (curl_errno($ch)) { throw new Exception('Curl error: ' . curl_error($ch)); } curl_close($ch); if ($httpCode !== 200) { throw new Exception('HTTP error: ' . $httpCode); } return json_decode($response, true); } } // Example usage try { $apiKey = 'your_api_key_here'; $urls = [ 'https://www.example.com/', 'https://www.tech-blog.com/' ]; $results = WebClassifAI::classifyUrls($urls, $apiKey); // Process results foreach ($results['results'] as $result) { $url = $result['url']; $scrapedSuccessfully = $result['scraped_successfully']; echo "\nURL: $url\n"; echo "Scraped successfully: " . ($scrapedSuccessfully ? 'true' : 'false') . "\n"; foreach ($result['predictions'] as $prediction) { echo "\nPrediction:\n"; if (isset($prediction['tier1'])) { $tier1 = $prediction['tier1']; printf( "Tier 1: %s (%s) - Confidence: %.2f\n", $tier1['name'], $tier1['code'], $tier1['confidence'] ); } if (isset($prediction['tier2'])) { $tier2 = $prediction['tier2']; printf( "Tier 2: %s (%s) - Confidence: %.2f\n", $tier2['name'], $tier2['code'], $tier2['confidence'] ); } } } } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; }

Error Handling

For production use, implement proper error handling:

public static function classifyUrls(array $urls, string $apiKey, string $taxonomy = 'iab-1.0'): array { try { // ... existing code ... } catch (Exception $e) { // Log the error error_log("WebClassifAI API error: " . $e->getMessage()); // Rethrow with more context throw new Exception( "Failed to classify URLs: " . $e->getMessage(), $e->getCode(), $e ); } }

Batch Processing

For optimal performance, send multiple URLs in a single request. We strongly recommend batching URLs (up to 500) in a single request:

// Process up to 500 URLs in a single request $urls = array_fill(0, 500, 'https://example.com'); $results = WebClassifAI::classifyUrls($urls, $apiKey);

Using Guzzle HTTP Client

For a more modern approach, you can use the Guzzle HTTP client:

<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; class WebClassifAIClient { private Client $client; private string $apiKey; public function __construct(string $apiKey) { $this->client = new Client([ 'base_uri' => 'https://api.classifai.com/', 'timeout' => 30.0, ]); $this->apiKey = $apiKey; } public function classifyUrls(array $urls, string $taxonomy = 'iab-1.0'): array { try { $response = $this->client->post('v1/classify', [ 'json' => [ 'urls' => $urls, 'api_key' => $this->apiKey, 'taxonomy' => $taxonomy ] ]); return json_decode($response->getBody(), true); } catch (GuzzleException $e) { throw new Exception( "Failed to classify URLs: " . $e->getMessage(), $e->getCode(), $e ); } } } // Example usage try { $client = new WebClassifAIClient('your_api_key_here'); $urls = ['https://www.example.com/']; $results = $client->classifyUrls($urls); print_r($results); } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; }

Asynchronous Processing

Important: We strongly recommend batching URLs in a single request (up to the 500 URL limit) for optimal performance. Only use async execution when your limits exceed 500 URLs or your architecture specifically requires it.

<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Promise; class AsyncWebClassifAIClient { private Client $client; private string $apiKey; public function __construct(string $apiKey) { $this->client = new Client([ 'base_uri' => 'https://api.classifai.com/', 'timeout' => 30.0, ]); $this->apiKey = $apiKey; } public function classifyUrlsAsync(array $batches, string $taxonomy = 'iab-1.0'): array { $promises = []; foreach ($batches as $index => $batch) { $promises[$index] = $this->client->postAsync('v1/classify', [ 'json' => [ 'urls' => $batch, 'api_key' => $this->apiKey, 'taxonomy' => $taxonomy ] ])->then( function ($response) { return json_decode($response->getBody(), true); } ); } return Promise\Utils::settle($promises)->wait(); } } // Example usage try { $client = new AsyncWebClassifAIClient('your_api_key_here'); // For best performance, process URLs in batches of up to 500 // Only split into multiple async requests if absolutely necessary $allUrls = array_fill(0, 1000, 'https://example.com'); $batchSize = 500; $batches = array_chunk($allUrls, $batchSize); $results = $client->classifyUrlsAsync($batches); foreach ($results as $index => $result) { if ($result['state'] === 'fulfilled') { $batchResults = $result['value']; echo "Processed batch " . ($index + 1) . " with " . count($batchResults['results']) . " URLs\n"; } else { echo "Error processing batch " . ($index + 1) . ": " . $result['reason']->getMessage() . "\n"; } } } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; }

Additional Resources

Last updated on