【问题标题】:file_get_contents won't return the source codefile_get_contents 不会返回源代码
【发布时间】:2015-09-10 23:20:46
【问题描述】:

当我执行这段代码时:

var_dump(file_get_contents('http://www.zahnarzt-gisler.ch'));

我得到这个错误:

警告:file_get_contents(http://www.zahnarzt-gisler.ch):未能 打开流:HTTP 请求失败! HTTP/1.1 403 禁止在 /home/httpd/vhosts/your-click.ch/httpdocs/wp-content/themes/your-click/ajax-request.php 在第 146 行 bool(false)

我不知道为什么它返回 false,因为当我更改 url 时,例如http://www.google.com 或任何其他 url,它将起作用并返回页面的源代码。

我想这一定是网址有问题,但我觉得这很奇怪,因为它的网址在线且可用。

【问题讨论】:

标签: php http-status-code-403


【解决方案1】:

网站所有者可以禁止您在不询问的情况下抓取他们的数据。

【讨论】:

    【解决方案2】:

    你可以只抓取页面,但你必须设置一个用户代理。卷曲是要走的路。

    file_get_contents() 是一个简单的螺丝刀。非常适合标头、HTTP 请求方法、超时、cookiejar、重定向和其他重要事项无关紧要的简单 GET 请求。

    <?php
    
    $config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
    
    $ch = curl_init();
    
    // Set the url, number of GET vars, GET data
    curl_setopt($ch, CURLOPT_URL, 'http://www.zahnarzt-gisler.ch');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_USERAGENT, $config['useragent']);
    
    // Execute request
    $result = curl_exec($ch);
    
    curl_close($ch);
    
    echo $result;
    
    ?>
    

    【讨论】:

    • 谢谢,我试试这个。
    猜你喜欢
    • 2014-09-14
    • 1970-01-01
    • 2018-05-03
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2011-05-23
    相关资源
    最近更新 更多