获取网页title可以通过正则表达式或者使用PHP内置函数来实现。
- 使用正则表达式获取网页title
可以使用正则表达式来匹配网页title标签中的内容。具体步骤如下:
- 使用file_get_contents函数获取网页内容
- 使用正则表达式匹配和之间的内容
- 返回匹配到的内容作为title
示例代码:
$url = "http://www.example.com";
$html = file_get_contents($url);
preg_match("/<title>(.*?)</title>/", $html, $matches);
$title = $matches[1];
- 使用PHP内置函数获取网页title
PHP提供了内置函数来获取网页的title,具体步骤如下:
- 使用file_get_contents函数获取网页内容
- 使用DOMDocument类加载网页内容
- 使用getElementsByTagName方法获取title标签
- 返回title标签中的内容作为title
示例代码:
$url = "http://www.example.com";
$html = file_get_contents($url);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$title = $dom->getElementsByTagName("title")->item(0)->nodeValue;