PHP code example of shanginn / cloudflare-browser

1. Go to this page and download the library: Download shanginn/cloudflare-browser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shanginn / cloudflare-browser example snippets


use Shanginn\CloudflareBrowser\CloudflareClient;
use Shanginn\CloudflareBrowser\CloudflareBrowser;

$accountId = getenv('CLOUDFLARE_ACCOUNT_ID');
$apiToken = getenv('CLOUDFLARE_API_TOKEN');

$client = new CloudflareClient($accountId, $apiToken);
$browser = new CloudflareBrowser($client);

use Shanginn\CloudflareBrowser\Requests\ScreenshotRequest;

$pngData = $browser->screenshot(new ScreenshotRequest(
    url: 'https://example.com',
    screenshotOptions: ['fullPage' => true]
));

file_put_contents('screenshot.png', $pngData);

use Shanginn\CloudflareBrowser\Requests\ScrapeRequest;

$results = $browser->scrape(new ScrapeRequest(
    url: 'https://news.ycombinator.com',
    elements: [
        ['selector' => '.titleline > a']
    ]
));

foreach ($results as $group) {
    foreach ($group->results as $element) {
        echo "Found: {$element->text} ({$element->attributes['href'] ?? ''})\n";
    }
}

use Spiral\JsonSchemaGenerator\Attribute\Field;

class ProductSchema 
{
    public function __construct(
        #[Field(title: 'Product Title', description: 'The main name of the item')]
        public string $title,

        #[Field(title: 'Price', description: 'Current price')]
        public float $price,
    ) {}
}

use Shanginn\CloudflareBrowser\Requests\JsonRequest;

/** @var ProductSchema $product */
$product = $browser->json(
    new JsonRequest(
        url: 'https://example-shop.com/item/123', 
        prompt: 'Extract the main product details'
    ),
    ProductSchema::class
);

echo "Product: {$product->title} - \${$product->price}\n";

use Shanginn\CloudflareBrowser\Requests\PdfRequest;
use Shanginn\CloudflareBrowser\Requests\Common\Viewport;

$pdfData = $browser->pdf(new PdfRequest(
    url: 'https://example.com',
    viewport: new Viewport(width: 1200, height: 800)
));

file_put_contents('page.pdf', $pdfData);

$html = $browser->content('https://example.com');
echo $html;

$markdown = $browser->markdown('https://example.com');
echo $markdown;

$links = $browser->links('https://example.com');

// Or get only internal links
$internalLinks = $browser->links(
    url: 'https://example.com',
    excludeExternal: true
);

use Shanginn\CloudflareBrowser\Requests\SnapshotRequest;

$snapshot = $browser->snapshot(new SnapshotRequest(
    url: 'https://example.com'
));

echo "Title: " . $snapshot->title . "\n";
echo "Content: " . $snapshot->content . "\n";