【发布时间】:2011-08-11 23:07:37
【问题描述】:
我在 PHP 中做了这个函数来获取页面的标题。我知道它可能看起来有点乱,但那是因为我是 PHP 的初学者。我之前在 if 中使用了preg_match("/<title>(.+)<\/title>/i",$returned_content,$m),但它并没有像我预期的那样工作。
function get_page_title($url) {
$returned_content = get_url_contents($url);
$returned_content = str_replace("\n", "", $returned_content);
$returned_content = str_replace("\r", "", $returned_content);
$lower_rc = strtolower($returned_content);
$pos1 = strpos($lower_rc, "<title>") + strlen("<title>");
$pos2 = strpos($lower_rc, "</title>");
if ($pos2 > $pos1)
return substr($returned_content, $pos1, $pos2-$pos1);
else
return $url;
}
这是我尝试使用上面的函数获取以下页面的标题时得到的: http://www.google.com -> “302 已移动” http://www.facebook.com -> ""http://www.facebook.com" http://www.revistabula.com/posts/listas/100-links-para-clicar-antes-de-morrer -> “http://www.revistabula.com/posts/listas/100-links-para-clicar-antes-de-morrer” (当我在链接末尾添加 / 时,我可以成功获得标题:“100 links para clicar antes de morrer | Revista Bula”)
我的问题是: - 当我尝试访问 google.com 时,我知道 google 正在重定向到我所在国家/地区的镜像,但是如何获取它重定向到的页面的标题? - 我的函数有什么问题导致它获得某些页面的标题,而不是其他页面的标题?
【问题讨论】:
-
get_url_contents($url)返回什么? -
get_url_contents()的代码是什么? -
我已经接受了一个答案。
get_url_contents()返回页面html代码。
标签: php