如何使用 php 在 url 中获取元标记

How to get meta tags in url using php

我写的代码是这样的:

$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);
$html = $data;

//parsing begins here:
$doc = new \DOMDocument();
@$doc->loadHTML($html);
$metas = $doc->getElementsByTagName('meta');

此代码目前有效,但某些 URL 会阻止 PHP 脚本以防止抓取。如何解决这个问题?

添加user_agent它会起作用

 curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

您可以使用以下方式提取所有元标记:

$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59