我在PHP中执行此功能以获取页面标题.我知道它可能看起来有点乱,但那是因为我是PHP的初学者.我preg_match("/<title>(.+)<\/title>/i",$returned_content,$m)之前在if中使用过它并没有像我预期的那样工作.
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;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用上述功能获取以下页面的标题时,我得到的是:http: //www.google.com - >"302 Moved" 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链接para clicar antes de morrer | Revista Bula")
我的问题是: - 当我尝试访问google.com时,我知道谷歌会重定向到我国家的镜像,但我怎样才能获得重定向到的页面标题? - 我的功能有什么问题让它获得某些页面的标题,而不是其他页面的标题?
HTTP客户端应遵循重定向.302状态代码表示您尝试获取的内容不在该位置,客户端应该按照Location:标题来确定它的位置.
你有两个问题.第一个不是重定向.如果你使用cURL,你可以通过设置它来使它遵循重定向:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
Run Code Online (Sandbox Code Playgroud)
有关完整解决方案,请参阅此问题:
第二个问题是您使用RegEx解析HTML. 不要那样做.请参阅此问题以获得更好的选择