HTML元标记用于提供有关HTML文档的结构化元数据。
元数据在<meta>标记中定义。
始终添加<meta>标记在<head>元素中。
其中,3个元元素用于指定网页,标题,描述和关键字的元数据。
可以使用PHP获取来自元标记的信息。
以下示例代码片段向我们展示如何使用PHP从外部URL获取标题和元标记。
<?php
//Web page URL
$url = 'https://www.onitroad.com/';
//Extract HTML using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
//Load HTML to DOM object
$dom = new DOMDocument();
@$dom->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 = '';
for($i=0; $i<$metas->length; $i++){
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description'){
$description = $meta->getAttribute('content');
}
if($meta->getAttribute('name') == 'keywords'){
$keywords = $meta->getAttribute('content');
}
}
echo "Title: $title". '<br/>';
echo "Description: $description". '<br/>';
echo "Keywords: $keywords";
?>
日期:2020-06-02 22:15:45 来源:oir作者:oir
