使用此功能:
function get_tags($adres)
{
$dom = new domDocument();
libxml_use_internal_errors(true);
if (!$dom->loadHTML($adres)) {
echo "Error";
} else echo "Load ok";
$html = new DOMXPath($dom);
$html->query('//title');
}
我尝试使用XPath获取并回显标题和关键字,描述,机器人元标记,但不知道如何以及如何查询元标记。
由于
答案 0 :(得分:1)
要检索标题,我使用:
$titles = $xpath->query('/html/head/title');
foreach ($titles as $title) {
$return['title'][] = $title->nodeValue;
}
因为DOM可能有多个<title />
标记,但不推荐使用。
然后我解析所有<meta />
标签,如下:
$metas = $xpath->query('/html/head/meta');
foreach ($metas as $meta) {
$name = strtolower($meta->getAttribute('name'));
if ($name == 'title' && (!isset($return['title']) || $return['title'] == '')) // There is such a thing as <meta name="title" \>
$return['title'][] = $meta->getAttribute('content');
if ($name == 'keywords')
$return['metakw'][] = $meta->getAttribute('content');
if ($name == 'description')
$return['metadesc'][] = $meta->getAttribute('content');
if ($name == 'robots')
$return['robots'][] = $meta->getAttribute('content');
}
但我想可以使用:
$metas_title = $xpath->query('/html/head/meta[@name="title"]');
$metas_desc = $xpath->query('/html/head/meta[@name="description"]');
$metas_kw = $xpath->query('/html/head/meta[@name="keywords"]');
$metas_robots = $xpath->query('/html/head/meta[@name="robots"]');