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

ant*_*isk 5 php url json file-get-contents http-status-code-404

我收到以下错误:

警告: 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 NOT FOUND in /home/DIR/htdocs/readability.php 第 23 行

通过一些 Echoes,我得到了函数解析的 URL,它很好且有效,我从浏览器发出请求,一切正常。

问题是我用 file_get_contents 得到了上述错误,我真的不明白为什么。

URL 有效并且该功能未被免费托管服务阻止(所以我不需要 Curl)。

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

这是我的代码:

<?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;
 }
}
?>
Run Code Online (Sandbox Code Playgroud)

小智 3

有时,网站会阻止爬虫(来自远程服务器)访问其页面。

为了解决这个问题,他们所做的就是欺骗浏览器标头。就像假装是 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

}
Run Code Online (Sandbox Code Playgroud)

然后我们可以这样称呼它:

$response = get_data($requesturl);
Run Code Online (Sandbox Code Playgroud)

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