尝试读取网页时,file_get_contents偶尔会返回空字符串

时间:2011-08-09 18:17:03

标签: php curl

我正在尝试使用file_get_contents()加载网页,并遇到问题。

基本上,我的网络应用程序将使用youtube数据api根据用户的查询搜索视频,然后阅读每个视频的youtube页面以查找api未提供的信息。我使用file_get_contents()来读取youtube页面,然后将文本加载到DOM解析器中。大多数时候,这就像一个魅力。但是,有时候,我会收到警告,说file_get_contents()返回一个空字符串(不是所有视频,只针对其中一些视频)。我知道我提供的网址是正确的,因为我回显了该网址的链接,它按预期工作。我将刷新页面,重新打开浏览器,切换到其他浏览器等,但没有任何工作。然后,我会离开这个东西一两个小时,回到它,它会再次神奇地工作!

以下是我的代码片段:

function processNext($int) {
    // this function processes the next $int videos from the youtube data api response ($xmlDoc)
    global $xmlDoc;
    $begin = count($_SESSION["results"]) - $_SESSION["start"] + 1;
        /* $_SESSION["results"] is the array of already-processed videos
           $_SESSION["start"] and $_SESSION["end"] are the indexes of the first and last videos in the $xmlDoc
        */
    $end = count($_SESSION["results"]) - $_SESSION["start"] + $int;

    for ($i = $begin; $i <= $end; $i++) {
        $video = $xmlDoc->entry[$i];
        $doc = new DOMDocument();
        $doc->strictErrorChecking = FALSE;
        libxml_use_internal_errors(true);

        // this is the line that is causing me problems
        $doc->loadHTML(file_get_contents(getWatchURL(getVidID($video->id)))); 

        $doc = $doc->documentElement;

               // then, do some processing on the $doc

    }
}

file_get_contents()是否可能超时? cURL是我正在做的更好的工具吗?

更新:我使用cURL获得了相同的结果。

1 个答案:

答案 0 :(得分:1)

看看$http_response_header。您可以检查请求的状态代码。如果它不是200,那么可能会出现问题。 More about status codes