PHP code example of ioodev / elephscraper

1. Go to this page and download the library: Download ioodev/elephscraper 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/ */

    

ioodev / elephscraper example snippets




oodev\Elephscraper\ElephScraper;

$scraper = new ElephScraper('https://example.com');

if (!$scraper->isValid()) {
    // Request failed (timeout, DNS error, 404, etc.) — will not throw a fatal error.
    die('Failed to load page: ' . $scraper->getError()?->getMessage());
}

echo $scraper->title();        // "Welcome to Example.com"
echo $scraper->description();  // "Example site for testing"
print_r($scraper->h1());       // ["Main Title", "News"]
print_r($scraper->openGraph());

$html = '<html><head><title>Static Page</title></head><body>...</body></html>';

$scraper = ElephScraper::fromHtml($html);

echo $scraper->title(); // "Static Page"

$scraper = new ElephScraper($url);

if (!$scraper->isValid()) {
    echo 'Error: ' . $scraper->getError()->getMessage();
    // continue to the next URL, etc.
}

use Ioodev\Elephscraper\Exceptions\ScraperException;

try {
    $scraper = new ElephScraper($url, ['throwOnError' => true]);
} catch (ScraperException $e) {
    echo 'Scraping failed: ' . $e->getMessage();
}

$scraper = new ElephScraper('https://example.com', [
    'timeout' => 20,
    'headers' => [
        'User-Agent' => 'MyBot/1.0',
        'Accept-Language' => 'en-US,en;q=0.9',
    ],
    'proxy' => 'http://localhost:8125',
    'verify' => false, // disable SSL verification (use with caution in production)
]);

$scraper = new ElephScraper('https://example.com', [
    'client' => $myMockedGuzzleClient,
]);

$scraper->title();          // ?string
$scraper->description();    // ?string
$scraper->keywords();       // ?string[] — comma-split result, already trimmed
$scraper->keywordString();  // ?string  — raw "content" attribute
$scraper->charset();        // ?string
$scraper->canonical();      // ?string
$scraper->contentType();    // ?string  — from meta http-equiv="Content-Type"
$scraper->author();         // ?string
$scraper->csrfToken();      // ?string  — checks <meta name="csrf-token">, falls back to <input name="csrf-token">
$scraper->image();          // ?string  — shortcut for og:image
$scraper->viewport();       // ?string[] — comma-split result from meta viewport
$scraper->viewportString(); // ?string

$scraper->openGraph();              // array<string,?string> — all common og: properties
$scraper->openGraph('og:title');    // ?string — a specific property

$scraper->twitterCard();                  // array<string,?string> — all common twitter: tags
$scraper->twitterCard('twitter:title');   // ?string — a specific property

$scraper->h1(); // ?string[]
$scraper->h2(); // ?string[]
$scraper->h3(); // ?string[]
$scraper->h4(); // ?string[]
$scraper->h5(); // ?string[]
$scraper->h6(); // ?string[]
$scraper->p();  // ?string[] — all <p> elements, trimmed

$scraper->ul(); // ?string[] — all <li> text inside <ul>
$scraper->ol(); // ?string[] — all <li> text inside <ol>

$scraper->images();       // ?string[] — all <img> src
$scraper->imageDetails(); // ?array<int, array{url:?string, alt_text:?string, title:?string}>

$scraper->links();       // ?string[] — all <a> href
$scraper->linkDetails();
// ?array<int, array{
//     url: ?string,
//     protocol: string,        // "https", "mailto", "" if relative, etc.
//     text: string,
//     title: string,
//     target: string,
//     rel: string[],
//     is_nofollow: bool,
//     is_ugc: bool,
//     is_noopener: bool,
//     is_noreferrer: bool,
// }>

$scraper->filter(
    element: 'div',
    attributes: ['id' => 'main'],
    multiple: false,
    extract: ['.title', '#desc', 'p'],
    returnHtml: false
);

$products = $scraper->filter(
    element: 'div',
    attributes: ['class' => 'product-card'],
    multiple: true,
    extract: ['.product-title', '.price'],
    returnHtml: false
);

// [
//     ['.product-title' => 'Wireless Mouse', '.price' => '$15.00'],
//     ['.product-title' => 'Mechanical Keyboard', '.price' => '$85.00'],
// ]

$scraper->filter(
    element: 'section',
    attributes: ['class' => 'hero'],
    returnHtml: true
);

$scraper->isValid();    // bool — whether the document loaded successfully
$scraper->getError();   // ?Throwable — the last exception, if any
$scraper->getHtml();    // ?string — raw HTML
$scraper->getCrawler(); // ?Symfony\Component\DomCrawler\Crawler
$scraper->getUrl();     // ?string — source URL (or base URL from loadHtml())

elephscraper/
├── .github/
│   └── workflows/
│       └── ci.yml              # GitHub Actions: tests + static analysis on PHP 8.0–8.3
├── examples/
│   ├── basic-usage.php
│   ├── custom-options.php
│   └── from-html-and-filter.php
├── src/
│   ├── Exceptions/
│   │   ├── InvalidUrlException.php
│   │   └── ScraperException.php
│   ├── Support/
│   │   └── CssSelectorBuilder.php   # safe CSS selector builder (escaping, id/class normalization)
│   └── ElephScraper.php             # main class
├── tests/
│   └── Unit/
│       ├── CssSelectorBuilderTest.php
│       └── ElephScraperTest.php
├── .gitignore
├── .php-cs-fixer.php
├── CHANGELOG.md
├── composer.json
├── LICENSE
├── phpstan.neon
├── phpunit.xml
└── README.md