本文实例讲述了php中file_get_contents高级用法,分享给大家供大家参考。
具体分析如下:首先解决file_get_contents的超时问题
在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线服务器而彻底放弃。
这里就简单介绍两种解决方法:
set_time_limit只是设定你的PHP程式的超时时间,而不是file_get_contents函数读取URL的超时时间。
立即学习“PHP免费学习笔记(深入)”;
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试是无效的。
真正的修改file_get_contents延时可以用resource $context的timeout参数。
PHP程序代码如下:
<p><php</p><p> $opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60 ) ); </p><p>$context = stream_context_create($opts); </p><p>$html =file_get_contents('http://www.scutephp.com', false, $context); </p><p>fpassthru($fp);</p>PHP程序代码如下:
<p><?php</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1298">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680203955338.png" alt="法语写作助手">
</a>
<div class="aritcle_card_info">
<a href="/ai/1298">法语写作助手</a>
<p>法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="法语写作助手">
<span>31</span>
</div>
</div>
<a href="/ai/1298" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="法语写作助手">
</a>
</div>
<p></p>$cnt=0;<br /> while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){<br /> $cnt++;<br />}以上方法对付超时已经OK了。
如下:PHP程序代码
<p><?php</p><p>function Post($url, $post = null){ </p><p>$context = array(); </p><p>if (is_array($post)) { </p><p>ksort($post); </p><p>$context['http'] = array ( 'timeout'=>60, 'method' => 'POST', 'content' => http_build_query($post, '', '&'), ); </p><p>} </p><p>return file_get_contents($url, false, stream_context_create($context)); } </p><p>$data = array ( 'name' => 'test', 'email' => , 'submit' => 'submit', ); </p><p>echo Post('http://www.scutephp.com', $data);</p>注意文档头的Set_time_out否则整个文档都得超时了。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号