Skip to content

Example: Twitter card parser ​

The built-in parsers do not read twitter:* tags. Some pages only have a Twitter card and no Open Graph. This example adds a parser for the card and uses it as a fallback after OgDomParser.

The parser ​

php
<?php

declare(strict_types=1);

namespace App;

use Tomaj\Scraper\Meta;
use Tomaj\Scraper\Parser\ParserInterface;

/**
 * Reads Twitter (X) card tags into the Open Graph fields of Meta.
 *
 * The built-in parsers do not read twitter:* tags. Put this parser after them, so the card is
 * only a fallback for pages without Open Graph:
 *
 *     $scraper->parse($html, [new OgDomParser(), new TwitterCardParser()]);
 */
final class TwitterCardParser implements ParserInterface
{
    #[\Override]
    public function parse(string $content): Meta
    {
        // a new Meta from every call: one parser instance is used for many pages
        $meta = new Meta();
        if ($content === '') {
            return $meta;
        }

        // the HTML5 parser of PHP 8.4: UTF-8 unless the page declares another charset,
        // LIBXML_NOERROR keeps parse errors of real-world markup from becoming warnings
        $dom = \Dom\HTMLDocument::createFromString($content, LIBXML_NOERROR);

        foreach ($dom->querySelectorAll('meta[name], meta[property]') as $tag) {
            // cards are written with name="twitter:…", some sites use property="twitter:…"
            $name = strtolower(($tag->getAttribute('name') ?: $tag->getAttribute('property')) ?? '');
            $value = $tag->getAttribute('content') ?? '';
            if ($value === '') {
                continue;
            }
            match ($name) {
                'twitter:title' => $meta->setOgTitle($value),
                'twitter:description' => $meta->setOgDescription($value),
                'twitter:image', 'twitter:image:src' => $meta->setOgImage($value),
                default => null,
            };
        }

        return $meta;
    }
}

It follows the rules for parsers: a new Meta per call, nothing thrown on bad markup, only found values set. It maps the card to the Open Graph fields, the closest ones Meta has.

The pages ​

html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Weekend hiking: Malá Fatra in winter</title>
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@outdoorsk">
<meta name="twitter:title" content="Malá Fatra in winter: five safe routes">
<meta name="twitter:description" content="Routes that stay open when there is snow, with times &amp; difficulty.">
<meta name="twitter:image" content="https://outdoor.example/img/mala-fatra.jpg">
<meta name="twitter:image:alt" content="Snow on the ridge of Malá Fatra">
</head>
<body></body>
</html>
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Weekend hiking: Slovak Paradise</title>
<meta property="og:title" content="Slovak Paradise: ladders and gorges">
<meta property="og:image" content="https://outdoor.example/img/paradise-og.jpg">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Slovak Paradise (Twitter title)">
<meta name="twitter:description" content="Suchá Belá gorge, step by step.">
<meta name="twitter:image" content="https://outdoor.example/img/paradise-square.jpg">
</head>
<body></body>
</html>

The code ​

php
<?php

declare(strict_types=1);

// A page that has only Twitter card tags, and one that has both Open Graph and a card.
// The custom TwitterCardParser (src/) fills the Open Graph fields only when they are missing.

require __DIR__ . '/vendor/autoload.php';

use App\TwitterCardParser;
use Tomaj\Scraper\Meta;
use Tomaj\Scraper\Parser\OgDomParser;
use Tomaj\Scraper\Scraper;

$base = $argv[1] ?? 'http://127.0.0.1:8403';

$scraper = new Scraper(['timeout' => 5]);
$show = static function (string $label, Meta $meta): void {
    echo "== {$label}\n";
    printf("%-15s %s\n", 'title', $meta->getTitle() ?? '(null)');
    printf("%-15s %s\n", 'og:title', $meta->getOgTitle() ?? '(null)');
    printf("%-15s %s\n", 'og:description', $meta->getOgDescription() ?? '(null)');
    printf("%-15s %s\n", 'og:image', $meta->getOgImage() ?? '(null)');
    echo "\n";
};

// the built-in parsers do not read twitter:* tags
$show('card-only.html, OgDomParser', $scraper->parseUrl($base . '/card-only.html', [new OgDomParser()]));

// the card fills the gaps
$parsers = [new OgDomParser(), new TwitterCardParser()];
$show('card-only.html, OgDomParser + TwitterCardParser', $scraper->parseUrl($base . '/card-only.html', $parsers));

// Open Graph wins where the page has it; the card adds only the description
$show('both.html, OgDomParser + TwitterCardParser', $scraper->parseUrl($base . '/both.html', $parsers));

Output ​

text
== card-only.html, OgDomParser
title           Weekend hiking: Malá Fatra in winter
og:title        (null)
og:description  (null)
og:image        (null)

== card-only.html, OgDomParser + TwitterCardParser
title           Weekend hiking: Malá Fatra in winter
og:title        Malá Fatra in winter: five safe routes
og:description  Routes that stay open when there is snow, with times & difficulty.
og:image        https://outdoor.example/img/mala-fatra.jpg

== both.html, OgDomParser + TwitterCardParser
title           Weekend hiking: Slovak Paradise
og:title        Slovak Paradise: ladders and gorges
og:description  Suchá Belá gorge, step by step.
og:image        https://outdoor.example/img/paradise-og.jpg

What to notice ​

  • With OgDomParser alone, the card-only page has a <title> and nothing else.
  • With the card parser after it, the Open Graph fields are filled from the card. &amp; in the description is decoded by the DOM parser.
  • On the page with both, Open Graph wins for the title and the image, because OgDomParser runs first; the card fills only the description, which the page has only as twitter:description.

What CI checks ​

The three results above: nothing from the card without the parser, the card as a fallback, and Open Graph taking precedence.

Released under the MIT License.