我正在使用PHP的get_meta_tags()
函数来获取不同网页的元标记。我想知道什么是获取网页<h1>
标签内容的最佳方式。我应该使用file_get_contents()
,还是有更好的方法?
是的,我会使用:
$page = file_get_contents('http://example.com');
$matches = array();
preg_match( '#<h1>(.*?)</h1>#', $page, $matches );
您的信息应在$matches
中
file_get_contents()
可以为您获取页面内容。一旦您有了内容,如何提取h1
标记就取决于您了。
您可以尝试使用一个简单的正则表达式来返回第一个h1
标记的内容:
$contents = file_get_contents($url);
preg_match_all("/<h1>(.*?)<'/h1>/", $contents, $matches);
$h1 = $matches[1];
但是,在处理HTML时,我更喜欢使用DOM解析器。PHP Simple HTML DOM Parser非常易于使用。类似于:
$contents = file_get_contents($url);
$html = str_get_html($contents);
$h1 = $html->find("h1")[0];
注意:我没有测试这些代码片段。只是一些样品,让你开始。
<h1>
标记不是元标记,因此不能使用get_meta_tags()
函数。HTML文档中的元标记是<head>
部分中的标记,其中包含有关页面的信息,而不是内容本身。
PHP.DOM可能是获得所需信息的最佳方式。这里有一个链接到一个不错的教程,应该可以让你很好地开始。
尝试使用简单HTML DOM。
代码:
<?php
require_once('simple_html_dom.php');
$raw = '<h1>blah</h1>'; // Set the raw HTML of the webpage here
$html = str_get_html($raw);
$h1 = $html->find('h1', 0)->plaintext;
echo $h1;
?>