How to Build a Twitter Card Preview Tool in PHP

Have you ever noticed, when you share any link to the social media platform like Twitter, Facebook or even Whatsapp instead of showing link as text it will render it properly containing details. Even sometimes it will show broken image which can impact click rate. In this guide, we will walk you through the entire process of creating your own custom Twitter Card Preview in PHP.

You can utilize this feature even for testing or checking how your web link looks like into different platforms and fix bugs before even facing them.

What is a Twitter Card Preview?

A Twitter Card Preview is the rich, informative box displays as card which automatically appears below a tweet when you share a link. Instead of just a plain URL, it fetches key information from the linked page and presents it in a visually appealing format.

For example, movies listing or detail page show banner image of movie as preview image using some meta tags. It helps increase trust and user experience. This card format is specially designed to work with Twitter (X). However, OpenGraph provides for all other plateforms.

Key Twitter Card Properties (Meta Tags)

Twitter generates preview card based on some specific information added by websites using meta tags. These meta tags contains all required information for Twitter card preview like site, title, description, image and it’s type. Here are the most essential properties:

    • twitter:card – Determines the type of card to display. Possible values are summary (small image) or summary_large_image (large, main image).
    • twitter:site – Identifies the @username of the Twitter account of the website.
    • twitter:creator – Identifies the @username of the content creator or author.
    • twitter:title – The title of your content, usually capped at 70 characters.
    • twitter:description – A short summary of the content, usually fewer than 200 characters.
    • twitter:image – The URL of the image you’d like to show in the card.

    Creating a Twitter Card Preview in PHP

    You can create Twitter card preview in PHP by extracting meta tags from webpages. As we already know, preview cards are generated using meta tags which are available for everyone. To extract meta information tags you can use different way. Checkout our post on Fetch Website Meta Tags with PHP to know all different ways to get meta information tag’s values.

    In this example, we will take URL from user as input and show twitter card preview for that URL. For simple understanding let’s move this meta extraction logic into different file called TwitterCardFetcher.php. So create this class file and modify it as below:

    <?php
    
    class TwitterCardFetcher
    {
        public static function fetch(string $url): array
        {
            $result = [
                'title' => '',
                'description' => '',
                'image' => '',
                'site' => '',
                'creator' => '',
                'card' => '',
                'error' => ''
            ];
    
            if (filter_var($url, FILTER_VALIDATE_URL) === false) {
                $result['error'] = 'Invalid URL provided.';
                return $result;
            }
    
            $html = @file_get_contents($url);
            if ($html === false) {
                $result['error'] = 'Unable to fetch content from the URL.';
                return $result;
            }
    
            $doc = new DOMDocument();
            @$doc->loadHTML($html);
    
            $metaTags = $doc->getElementsByTagName('meta');
    
            $metaData = [];
            foreach ($metaTags as $meta) {
                $key = strtolower($meta->getAttribute('name') ?: $meta->getAttribute('property'));
                if ($key && $meta->hasAttribute('content')) {
                    $metaData[$key] = $meta->getAttribute('content');
                }
            }
    
            $twitterDetected = isset($metaData['twitter:card']);
    
            $result['card'] = $metaData['twitter:card'] ?? '';
            $result['title'] = $metaData['twitter:title'] ?? $metaData['title'] ?? '';
            $result['description'] = $metaData['twitter:description'] ?? $metaData['description'] ?? '';
            $result['image'] = $metaData['twitter:image'] ?? $metaData['og:image'] ?? '';
            $result['site'] = $metaData['twitter:site'] ?? '';
            $result['creator'] = $metaData['twitter:creator'] ?? '';
    
            foreach ($result as $key => $value) {
                if (strpos($key, 'twitter') !== false && !empty($value)) {
                    $twitterDetected = true;
                    break;
                }
            }
    
            if (!$twitterDetected) {
                $result['error'] = 'No Twitter card meta data found on this URL.';
            }
    
            return $result;
        }
    }

    As you can see, we have created simple class file with only one static method. The fetch method will simply take URL as parameter and return meta information required for generating Twitter preview card in PHP.

    First, It will validate URL into using filter_var and set error message for invalid URL. If URL is valid then it will get it’s content or HTML code from server then extract meta tags from content.

    Here, if there are twitter tags then it will fetch these data and return it otherwise it will return error. If some data are missing like page title, meta description or even image then it will find and set into response. Let’s create markup for user input and showing Twitter preview card using PHP:

    <?php
    require_once 'TwitterCardFetcher.php';
    ?>
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <title>Twitter Card Preview Tool</title>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
      <style>
        .card-preview {
          max-width: 600px;
          margin-top: 20px;
        }
    
        .card-preview img {
          width: 100%;
          height: auto;
        }
      </style>
    </head>
    
    <body class="p-4">
      <div class="container">
        <h2>Twitter Card Preview Tool</h2>
        <form method="post">
          <div class="mb-3">
            <input type="text" name="url" class="form-control" placeholder="Enter website URL" required value="<?php if (!empty($_POST['url'])) echo htmlspecialchars($_POST['url']); ?>">
          </div>
          <button type="submit" class="btn btn-primary">Generate Preview</button>
        </form>
    
        <?php
        if (!empty($_POST['url'])) {
          $url = $_POST['url'];
          $cardData = TwitterCardFetcher::fetch($url);
    
          if (!empty($cardData['error'])) {
            echo '<div class="alert alert-danger mt-4">' . htmlspecialchars($cardData['error']) . '</div>';
          } else {
            echo '<div class="card card-preview mt-4">';
            if (!empty($cardData['image'])) {
              echo '<img src="' . htmlspecialchars($cardData['image']) . '" class="card-img-top" alt="Card Image">';
            }
            echo '<div class="card-body">';
            echo '<h5 class="card-title">' . htmlspecialchars($cardData['title']) . '</h5>';
            echo '<p class="card-text">' . htmlspecialchars($cardData['description']) . '</p>';
            if (!empty($cardData['site'])) {
              echo '<p class="card-text"><small class="text-muted">Site: ' . htmlspecialchars($cardData['site']) . '</small></p>';
            }
            if (!empty($cardData['creator'])) {
              echo '<p class="card-text"><small class="text-muted">Creator: ' . htmlspecialchars($cardData['creator']) . '</small></p>';
            }
            echo '</div></div>';
          }
        }
        ?>
      </div>
    </body>
    
    </html>

    It will show user an simple for and take URL as user input and show preview card for that URL.

    Twitter preview card in PHP output

    Conclusion

    Congratulations, you have now learned how to build Twitter card preview with PHP. This easy tool makes it clear how social websites create link previews and provides you with a useful tool for testing your own web pages. Creating a Twitter card preview tool with PHP allows you to guarantee your content is always presented at its best when shared, encouraging more engagement and traffic returning to your site. You can now add more functionality to this tool such as error handling or support for other meta tags like Open Graph.