Files
crawlshot/example_usage.php
2025-08-11 02:35:35 +08:00

73 lines
2.3 KiB
PHP

<?php
require_once 'vendor/autoload.php';
use Crawlshot\Laravel\CrawlshotClient;
// Initialize client
$client = new CrawlshotClient('https://crawlshot.test', 'your-api-token');
// Example 1: Fluent interface with webhook
$crawlJob = $client->crawl('https://example.com')
->webhookUrl('https://myapp.com/webhook')
->webhookEventsFilter(['completed', 'failed'])
->blockAds(true)
->timeout(30)
->create();
echo "Crawl job created: " . $crawlJob->getUuid() . "\n";
echo "Status: " . $crawlJob->getStatus() . "\n";
echo "Is queued: " . ($crawlJob->isQueued() ? 'yes' : 'no') . "\n";
// Example 2: Check status with typed response
$crawlStatus = $client->getCrawlStatus($crawlJob->getUuid());
if ($crawlStatus->isCompleted()) {
echo "HTML content: " . substr($crawlStatus->getResultRaw(), 0, 100) . "...\n";
echo "Download URL: " . $crawlStatus->getResultUrl() . "\n";
// Direct download
$htmlContent = $crawlStatus->downloadHtml();
} elseif ($crawlStatus->isFailed()) {
echo "Error: " . $crawlStatus->getError() . "\n";
} else {
echo "Still processing...\n";
// Refresh status
$crawlStatus->refresh();
}
// Example 3: Screenshot with fluent interface
$shotJob = $client->shot('https://example.com')
->webhookUrl('https://myapp.com/webhook')
->webhookEventsFilter(['completed'])
->viewportSize(1920, 1080)
->quality(90)
->create();
$shotStatus = $client->getShotStatus($shotJob->getUuid());
if ($shotStatus->isCompleted()) {
echo "Image format: " . $shotStatus->getFormat() . "\n";
echo "Dimensions: " . implode('x', $shotStatus->getDimensions()) . "\n";
echo "File size: " . $shotStatus->getSize() . " bytes\n";
// Get base64 data or download directly
$imageData = $shotStatus->getImageData();
$imageFile = $shotStatus->downloadImage();
}
// Example 4: Webhook error management
$errors = $client->listWebhookErrors();
foreach ($errors['jobs'] as $errorJob) {
echo "Failed webhook for job: " . $errorJob['uuid'] . "\n";
// Retry or clear
$client->retryWebhook($errorJob['uuid']);
// OR
// $client->clearWebhookError($errorJob['uuid']);
}
// Example 5: Raw response access (backward compatibility)
$rawResponse = $crawlStatus->getRawResponse();
echo "Raw response: " . json_encode($rawResponse, JSON_PRETTY_PRINT) . "\n";