Home / Get meta tags from an HTML file with PHP

Get meta tags from an HTML file with PHP

While researching some functions for a PHP article I’m writing I came across the get_meta_tags() function and decided to write a quick post about it.

get_meta_tags() function

The way this function works is to take the filename passed as the first parameter (which can be a URL if allow_url_fopen is on in the PHP confuguration) and then find all the <meta> tags until the closing </head> tag. Any that are in the following form will be returned in an array:

<meta name="KEY" content="VALUE">

The meta name (KEY in the above example) will be the array’s key and the content (VALUE in the above example) will be the value.

So if the start of the HTML at http://www.example.com/ contained the following:

<html>
<head>
<title>Welcome to example.com</title>
<meta name="keywords" content="the keywords meta tag is redundant but people still include it">
<meta name="description" content="here's the meta description for my fictional example.com homepage">
</head>

Then doing this:

$tags = get_meta_tags('http://www.healthy.co.nz/');
print_r($tags);

will output this:

Array
(
    [keywords] => the keywords meta tag is redundant but people still include it
    [description] => here's the meta description for my fictional example.com homepage
)

As far as I can tell from testing this myself, any meta tag in the form <meta name="KEY" content="VALUE"> will be included in the array returned.