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.
Here's an example using regular expressions:
<?php
$url = "https://www.jsonplaceholder.com";
$html = file_get_contents($url);
preg_match("/<title>(.+)<\/title>/i", $html, $title);
preg_match_all('/<meta .*?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>";
}
Watch a video course
Learn object oriented PHP
Alternatively, you can use a DOM parsing library such as PHP's DOMDocument class:
<?php
$dom = new DOMDocument();
@$dom->loadHTML(file_get_contents($url));
$title = $dom->getElementsByTagName('title')->item(0)->nodeValue;
$meta = $dom->getElementsByTagName('meta');
echo "Titel: " . $title;
foreach ($meta as $tag) {
echo "Meta " . $tag->getAttribute('name') . ": " . $tag->getAttribute('content') . "<br>";
}
You may also want to consider using a package like php-web-scraper
which is a simple and efficient way to scrape web pages and extract information.