替代file_get_contents读取远程网页

file_get_contents有时因为服务器PHP配置问题不能读取成功,可用下面的函数替代

导致file_get_contents不能成功读取的配置为PHP.ini文件的allow_url_fopen = On未打开

程序代码 程序代码

$str=get_http('www.520music.com','/MusicList/520music.com_14185.htm');

function get_http($host,$url){
    $fp=fsockopen($host,80,$errno,$errstr,30);
    if(!$fp) echo "$errstr ($errno)";
    else{
        $out="GET $url HTTP/1.0\r\n";
        $out.="Host: $host\r\n";
        $out.="Connection: Close\r\n\r\n";

        fputs($fp,$out);
        $str="";
        while(!feof($fp)) $str.=fgets($fp,128);
        fclose($fp);
    }
    return $str;
}


另外亦可通过循环方式读取

程序代码 程序代码

$cnt=0;
while($cnt < 3 && ($body=@file_get_contents("$url"))===FALSE) $cnt++;
if(empty($body))
{
    echo file_get_contents("$htmlurl");
    exit;
}


[本日志由 shao65308 于 2010-03-31 06:59 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: PHP 函数
相关日志:
评论: 0 | 引用: 0 | 查看次数: 3461
发表评论
你没有权限发表评论!