file_get_contents高級用法,file_get_contents_PHP教程

WBOY
풀어 주다: 2016-07-13 10:18:24
원래의
871명이 탐색했습니다.

file_get_contents高級用法,file_get_contents

首先解決file_get_contents的超時問題,在超時返回錯誤後就象js中的settimeout那樣進行一次嘗試,錯誤超過3次或者5次後就確認為無法連線伺服器而徹底放棄。
這裡就簡單介紹兩種解決方法:

一、增加超時的時間限制

注意:set_time_limit只是設定你的PHP程式的超時時間,而不是file_get_contents函數讀取URL的超時時間。
我一開始以為set_time_limit也能影響到file_get_contents,後來經測試是無效的。真正的修改file_get_contents延時可以用resource $context的timeout參數:
PHP程式碼

    $opts = array(
        'http'=>array(
            'method'=>"GET",
            'timeout'=>60,
        )
    );

    $context = stream_context_create($opts);

    $html =file_get_contents('http://www.example.com', false, $context);
    fpassthru($fp);

二、多次嘗試

PHP程式碼
    $cnt=0;
    while($cnt       $cnt++;
    }

以上方法對付超時已經OK了。接下來演示一下用file_get_contents實現Post,如下:
PHP程式碼

    function Post($url, $post = null){
        $context = array();
        if (is_array($post)) {
            ksort($post);

            $context['http'] = array (
                'timeout'=>60,
                'method' => 'POST',
                'content' => http_build_query($post, '', '&'),
             );
        }

        return file_get_contents($url, false, stream_context_create($context));
    }

    $data = array (
        'name' => 'test',
        'email' => 'test@gmail.com',
        'submit' => 'submit',
     );

     echo Post('http://www.example.com', $data);

注意檔案頭的Set_time_out否則整個檔案都得超時了

file_get_contents的用法

file_get_contents — 将整个文件读入一个字符串

说明
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

Note: 如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。

Note: context 参数可以用 NULL 来忽略。
 

怎运用php 的 file_get_contents

file_get_contents() 读取一个文件中的内容,包括远程文件!!
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法!!
echo file_get_contents('www.baidu.com');
?>
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/883439.htmlTechArticlefile_get_contents高級用法,file_get_contents 首先解決file_get_contents的超時問題,在超時返回錯誤後就象js中的settimeout那樣進行一次嘗試,錯誤超過...
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!