使用浏览器打开URL并且URL有效时,file_get_contents返回404

时间:2014-01-29 18:15:10

标签: php json url http-status-code-404 file-get-contents

我收到以下错误:

  

警告:   的file_get_contents(https://www.readability.com/api/content/v1/parser?url=http://www.redmondpie.com/ps1-and-ps2-games-will-be-playable-on-playstation-4-very-soon/?utm_source=dlvr.it&utm_medium=twitter&token=MYAPIKEY)   [function.file-get-contents]:无法打开流:HTTP请求   失败! HTTP / 1.1 404未找到   /home/DIR/htdocs/readability.php   在第23行

使用一些Echoes我得到了该函数解析的URL,它很好并且有效,我从浏览器中执行请求并且没问题。

问题是我用file_get_contents得到了Error Above,我真的不明白为什么。

免费托管服务的网址有效,功能未阻止(所以我不需要卷曲)。

如果有人能在我的代码中发现错误,我将不胜感激! 感谢...

这是我的代码:

<?php

class jsonRes{
    public $url;
    public $author;
    public $url;
    public $image;
    public $excerpt;
}

function getReadable($url){
 $api_key='MYAPIKEY';
 if(isset($url) && !empty($url)){

    // I tried changing to http, no 'www' etc... -THE URL IS VALID/The browser opens it normally-

    $requesturl='https://www.readability.com/api/content/v1/parser?url=' . urlencode($url) . '&token=' . $api_key;
    $response = file_get_contents($requesturl);   // * here the code FAILS! *

    $g = json_decode($response);

    $article_link=$g->url;
    $article_author='';
    if($g->author != null){
       $article_author=$g->author;
    }

    $article_url=$g->url;
    $article_image=''; 
    if($g->lead_image_url != null){
        $article_image=$g->lead_image_url;
    }
    $article_excerpt=$g->excerpt;

    $toJSON=new jsonRes();
    $toJSON->url=$article_link;
    $toJSON->author=$article_author;
    $toJSON->url=$article_url;
    $toJSON->image=$article_image;
    $toJSON->excerpt->$article_excerpt;

    $retJSONf=json_encode($toJSON);
    return $retJSONf;
 }
}
?>

1 个答案:

答案 0 :(得分:1)

有时,网站会阻止抓取工具(来自远程服务器)访问其网页。

他们解决这个问题的方法是欺骗浏览器标题。就像假装是Mozilla Firefox而不是他们那些偷偷摸摸的PHP网络刮刀一样。

这是一个使用cURL库来完成的功能。

function get_data($url) {

$userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}
else{
    return $html;
}

//End of cURL function

}

然后将其称为如下:

$response = get_data($requesturl);

与File_get_contents相比,Curl在获取远程内容和错误检查方面提供了更多选项。如果您想进一步自定义,请在此处查看cURL选项列表 - Abridged list of cURL options