and

How to Get Title and Metadata (meta tags) from URL using PHP

In this article, I am going to show you how to get webpage Titles and Meta tags from external website URLs using PHP. Scroll down to the page so you can see the full source code available for this.

Mostly, All external websites are used to specify the 3 common metadata for the web page are page title, page description, and page keywords. These all meta tags information fetched using PHP. The page description and page keywords within tag and page title is tag.

 
codeat21
loadHTML($data); // Parse DOM to get Title data $nodes = $dom->getElementsByTagName('title'); $title = $nodes->item(0)->nodeValue; // Parse DOM to get meta data $metas = $dom->getElementsByTagName('meta'); $description = ''; $keywords = ''; $site_name = ''; $image = ''; for($i=0; $ilength; $i++)< $meta = $metas->item($i); if($meta->getAttribute('name') == 'description')< $description = $meta->getAttribute('content'); > if($meta->getAttribute('name') == 'keywords')< $keywords = $meta->getAttribute('content'); > if($meta->getAttribute('property') == 'og:site_name')< $site_name = $meta->getAttribute('content'); > if($meta->getAttribute('property') == 'og:image')< $image = $meta->getAttribute('content'); > > echo "Title: $title". '

'; echo "Description: $description". '

'; echo "Keywords: $keywords". '

'; echo "site_name: $site_name". '

'; echo "image: $image"; ?>

Output

  • Title: Home — codeat21.com — Web Designing and Development Tutorials Website.
  • Description: codeat21.com is a web designing and development tutorials website. Learn Web Development, HTML, CSS, PHP, MySQL, JavaScript, Node JS, React JS, jQuery, etc..
  • Keywords:
  • site_name: codeat21.com — Web Designing and Development Tutorials Website.
  • image:
  • Get meta tags from URL
  • Get meta tags from url javascript
  • Get_meta_tags
  • how to add meta tags in php website
  • How to add meta tags dynamically in PHP
  • Php get title from url
  • How to add meta title and description in php
  • php get page title from url, curl get meta tags
  • get og meta tags javascript
  • dynamically change og meta tags

Recent Posts

Источник

stream_get_meta_data

  • timed_out (bool) — true if the stream timed out while waiting for data on the last call to fread() or fgets() .
  • blocked (bool) — true if the stream is in blocking IO mode. See stream_set_blocking() .
  • eof (bool) — true if the stream has reached end-of-file. Note that for socket streams this member can be true even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.
  • unread_bytes (int) — the number of bytes currently contained in the PHP’s own internal buffer.

Examples

Example #1 stream_get_meta_data() example using fopen() with http

if (! $fp = fopen ( $url , ‘r’ )) trigger_error ( «Unable to open URL ( $url )» , E_USER_ERROR );
>

$meta = stream_get_meta_data ( $fp );

The above example will output something similar to:

array(10) < 'timed_out' =>bool(false) 'blocked' => bool(true) 'eof' => bool(false) 'wrapper_data' => array(13) < [0] =>string(15) "HTTP/1.1 200 OK" [1] => string(11) "Age: 244629" [2] => string(29) "Cache-Control: max-age=604800" [3] => string(38) "Content-Type: text/html; charset=UTF-8" [4] => string(35) "Date: Sat, 20 Nov 2021 18:17:57 GMT" [5] => string(24) "Etag: "3147526947+ident"" [6] => string(38) "Expires: Sat, 27 Nov 2021 18:17:57 GMT" [7] => string(44) "Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT" [8] => string(22) "Server: ECS (chb/0286)" [9] => string(21) "Vary: Accept-Encoding" [10] => string(12) "X-Cache: HIT" [11] => string(20) "Content-Length: 1256" [12] => string(17) "Connection: close" > 'wrapper_type' => string(4) "http" 'stream_type' => string(14) "tcp_socket/ssl" 'mode' => string(1) "r" 'unread_bytes' => int(1256) 'seekable' => bool(false) 'uri' => string(23) "http://www.example.com/" >

Example #2 stream_get_meta_data() example using stream_socket_client() with https

$streamContext = stream_context_create (
[
‘ssl’ => [
‘capture_peer_cert’ => true ,
‘capture_peer_cert_chain’ => true ,
‘disable_compression’ => true ,
],
]);

$client = stream_socket_client (
‘ssl://www.example.com:443’ ,
$errorNumber ,
$errorDescription ,
40 ,
STREAM_CLIENT_CONNECT ,
$streamContext
);

$meta = stream_get_meta_data ( $client );

The above example will output something similar to:

array(8) < 'crypto' =>array(4) < 'protocol' =>string(7) "TLSv1.3" 'cipher_name' => string(22) "TLS_AES_256_GCM_SHA384" 'cipher_bits' => int(256) 'cipher_version' => string(7) "TLSv1.3" > 'timed_out' => bool(false) 'blocked' => bool(true) 'eof' => bool(false) 'stream_type' => string(14) "tcp_socket/ssl" 'mode' => string(2) "r+" 'unread_bytes' => int(0) 'seekable' => bool(false) >

Notes

Note:

This function does NOT work on sockets created by the Socket extension.

See Also

User Contributed Notes 4 notes

In PHP 5.4.24 and 5.4.25, this command does not correctly return the stream blocking status. It always returns [‘blocked’] == 1 regardless of the actual blocking mode. A call to stream_set_blocking($stream, 0) will succeed (return TRUE) and subsequent calls to stream_get_contents($stream) will NOT block, even though a call to stream_get_meta_data($stream) will return ‘blocked’ == 1. Hopefully this will save some people a bunch of debugging time.

See bug report #47918 for more information (http://bugs.php.net/bug.php?id=47918).

Proof:
$d = array(
0 => array( ‘pipe’ , ‘r’ ),
1 => array( ‘pipe’ , ‘w’ ),
2 => array( ‘file’ , ‘error.log’ , ‘a’ )
);

$p = proc_open ( ‘php -S localhost:8000’ , $d , $pipes );

if (! is_resource ( $p )) die( «proc_open() failed\n» );

// Set child’s stdout pipe to non-blocking.
if (! stream_set_blocking ( $pipes [ 1 ], 0 )) die( «stream_set_blocking() failed\n» );
>
else echo «Non-blocking mode should be set.\n» ;
>

// View the status of that same pipe.
// Note that ‘blocked’ is 1! This appears to be wrong.
print_r ( stream_get_meta_data ( $pipes [ 1 ]));

// Try to read something. This will block if in blocking mode.
// If it does not block, stream_set_blocking() worked but
// stream_get_meta_data() is lying about blocking mode.
$data = stream_get_contents ( $pipes [ 1 ]);

echo «data = ‘ $data ‘\n» ;
?>

Output:
Non-blocking mode should be set.
Array
(
[stream_type] => STDIO
[mode] => r
[unread_bytes] => 0
[seekable] =>
[timed_out] =>
[blocked] => 1 // [eof] =>
)
data = » // this would never appear if we blocked.

Below is a function I wrote to pull the «Last-Modified» header from a given URL. In PHP version 4.3 and above, it takes advantage of the stream_get_meta_data function, and in older version it uses a conventional GET procedure. On failure to connect to $url, it returns NULL. If the server does not return the Last-Modified header, it returns the current time. All times are returned in PHP’s integer format (seconds since epoch).

$last_modified = stream_last_modified(‘http://www.php.net/news.rss’);
if (!is_null($last_modified))
if ($last_modified < time()-3600) //Older than an hour
echo ‘URL is older than an hour.’;
else
echo ‘URL is fairly new.’;
else
echo ‘Invalid URL!’;

$meta = stream_get_meta_data($fp);
for ($j = 0; isset($meta[‘wrapper_data’][$j]); $j++)
if (strstr(strtolower($meta[‘wrapper_data’][$j]), ‘last-modified’))
$modtime = substr($meta[‘wrapper_data’][$j], 15);
break;
>
>
fclose($fp);
>
else
$parts = parse_url($url);
$host = $parts[‘host’];
$path = $parts[‘path’];

if (!($fp = @fsockopen($host, 80)))
return NULL;

$req = «HEAD $path HTTP/1.0\r\nUser-Agent: PHP/».phpversion().»\r\nHost: $host:80\r\nAccept: */*\r\n\r\n»;
fputs($fp, $req);

while (!feof($fp))
$str = fgets($fp, 4096);
if (strstr(strtolower($str), ‘last-modified’))
$modtime = substr($str, 15);
break;
>
>
fclose($fp);
>
return isset($modtime) ? strtotime($modtime) : time();
>

here is just an example how to read out all meta data.
how ever I found out that the «seekable»-entry doesn’t exist in most of the streaming media files.

if (!($fp = @fopen($url, ‘r’)))
return NULL;

Источник

get_meta_tags

Открывает filename и разбирает его строка за строкой в поисках тегов . Разбор файла останавливается на теге .

Список параметров

Путь к HTML файлу, строка. Может быть как локальным файлом, так и URL .

Пример #1 Что обрабатывает функция get_meta_tags()

(обратите внимание на символы конца строки — PHP использует для разбора строк функции, встроенные в операционную систему, поэтому файлы, созданные в MacOS не будут правильно обрабатываться на Unix).

Если use_include_path равен TRUE , PHP будет искать файл используя стандартные пути поиска из директивы php.ini include_path. Это актуально только для локальных файлов, но не для URL.

Возвращаемые значения

Возвращает ассоциативный массив со значениями разобранных мета-тегов.

Значение атрибута name становится ключом массива, а значение атрибута content — значением этого элемента. Вы можете использовать стандартные функции работы с массивами для обхода или доступа к конкретным значениям. Специальные символы в именах (ключах массива) заменяются на ‘_’, и ключи приводятся к нижнему регистру. Если два мета-тега имеют одинаковые имена, будет возвращен только последний.

Примеры

Пример #2 Что возвращает функция get_meta_tags()

// Предположим, что указанные выше мета-теги расположены на www.example.com
$tags = get_meta_tags ( ‘http://www.example.com/’ );

// Обратите внимание, что ключи приведены к нижнему регистру, а
// точки (‘.’) в ключах заменены на ‘_’
echo $tags [ ‘author’ ]; // name
echo $tags [ ‘keywords’ ]; // php documentation
echo $tags [ ‘description’ ]; // a php manual
echo $tags [ ‘geo_position’ ]; // 49.33;-86.59
?>

Примечания

Замечание:

Обрабатываются только мета-теги с атрибутом name. Кавычки не требуются.

Смотрите также

  • htmlentities() — Преобразует все возможные символы в соответствующие HTML-сущности
  • urlencode() — URL-кодирование строки

Источник

get_meta_tags

Открывает filename и разбирает его строка за строкой в поисках тегов . Разбор файла останавливается на теге .

Список параметров

Путь к HTML файлу, строка. Может быть как локальным файлом, так и URL .

Пример #1 Что обрабатывает функция get_meta_tags()

(обратите внимание на символы конца строки — PHP использует для разбора строк функции, встроенные в операционную систему, поэтому файлы, созданные в MacOS не будут правильно обрабатываться на Unix).

Если use_include_path равен TRUE , PHP будет искать файл используя стандартные пути поиска из директивы php.ini include_path. Это актуально только для локальных файлов, но не для URL.

Возвращаемые значения

Возвращает ассоциативный массив со значениями разобранных мета-тегов.

Значение атрибута name становится ключом массива, а значение атрибута content — значением этого элемента. Вы можете использовать стандартные функции работы с массивами для обхода или доступа к конкретным значениям. Специальные символы в именах (ключах массива) заменяются на ‘_’, и ключи приводятся к нижнему регистру. Если два мета-тега имеют одинаковые имена, будет возвращен только последний.

Примеры

Пример #2 Что возвращает функция get_meta_tags()

// Предположим, что указанные выше мета-теги расположены на www.example.com
$tags = get_meta_tags ( ‘http://www.example.com/’ );

// Обратите внимание, что ключи приведены к нижнему регистру, а
// точки (‘.’) в ключах заменены на ‘_’
echo $tags [ ‘author’ ]; // name
echo $tags [ ‘keywords’ ]; // php documentation
echo $tags [ ‘description’ ]; // a php manual
echo $tags [ ‘geo_position’ ]; // 49.33;-86.59
?>

Примечания

Замечание:

Обрабатываются только мета-теги с атрибутом name. Кавычки не требуются.

Смотрите также

  • htmlentities() — Преобразует все возможные символы в соответствующие HTML-сущности
  • urlencode() — URL-кодирование строки

Источник

Читайте также:  Пример веб-страницы с php кодом
Оцените статью