W3docs

Getting title and meta tags from external website

In PHP, you can use the file_get_contents() function to retrieve the HTML code of a website, and then use regular expressions or a DOM parsing library to extract the title and meta tags.

In PHP, you can use the file_get_contents() function to retrieve the HTML code of a website, and then use regular expressions or a DOM parsing library to extract the title and meta tags.

Here's an example using regular expressions:

Example of using file_get_contents() function to retrieve the HTML code of a website in PHP

<?php

$url = "https://www.jsonplaceholder.com";
$html = @file_get_contents($url);
if ($html === false) {
    die('Failed to fetch URL');
}
preg_match("/<title>(.+)<\/title>/i", $html, $title);
preg_match_all('/<meta\s+[^>]*name=["\']?([^"\']+)["\']?[^>]*content=["\']([^"\']+)["\']?[^>]*\/?>/i', $html, $meta);

echo "Title: " . $title[1];
for ($i = 0; $i < count($meta[1]); $i++) {
  echo "Meta " . $meta[1][$i] . ": " . $meta[2][$i] . "<br>";
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Alternatively, you can use a DOM parsing library such as PHP's DOMDocument class:

Example of using a DOM parsing library such as PHP's DOMDocument to retrieve the HTML code of a website in PHP

<?php

$url = "https://www.jsonplaceholder.com";
$html = @file_get_contents($url);
if ($html === false) {
    die('Failed to fetch URL');
}

$dom = new DOMDocument();
@$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue;
$meta = $dom->getElementsByTagName('meta');

echo "Title: " . $title;
foreach ($meta as $tag) {
  echo "Meta " . $tag->getAttribute('name') . ": " . $tag->getAttribute('content') . "<br>";
}

You may also want to consider using a package like symfony/dom-crawler, which provides a robust and standard way to scrape web pages and extract information.