【问题标题】:PHP to retrieve title from a webpagePHP从网页中检索标题
【发布时间】:2014-10-19 13:08:33
【问题描述】:

我有一个 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 中。 谢谢!

【问题讨论】:

  • 定义“无法访问网页”
  • 如果去掉file_get_contents()前面的@会怎样?
  • @Reeno 同样的警告出来了。
  • 因为你的ip不允许通过alibaba.com服务器上的curlfile_get_contents访问alibab.com

标签: php curl


【解决方案1】:

你必须设置 user_agent

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

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2011-08-23
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多