PHP从网页中检索标题

时间:2014-08-26 09:03:01

标签: php curl

我有一个PHP代码来检索网页中的标题。但是,由于某种原因,我无法访问此特定网站(适用于其他网站)(无服务器响应)。为什么这只发生在这个网站上?我应该使用其他什么方法?我试过cURL但仍无法访问该网页。

这是我的代码:

<?php

function page_title($url) {

    $page = @file_get_contents($url);

    if (!$page) return null;

    $matches = array();

    if (preg_match('/<title>(.*?)<\/title>/', $page, $matches)) {
        return $matches[1];
    }
    else {
        return null;
    }
}


echo page_title('http://www.alibaba.com/');

?>

它出来了: 警告:file_get_contents(http://www.alibaba.com):无法打开流:连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接主机无法响应而建立连接失败。在第16行的C:\ xampp \ htdocs \ myPHP \ index.php中。 谢谢!

1 个答案:

答案 0 :(得分:2)

您必须设置user_agent

$page = file_get_contents($url,false,stream_context_create(array("http" => array("user_agent" => "any"))));
相关问题