duanniu3385 2012-06-22 12:53
浏览 14
已采纳

在PHP中,我如何阅读不可靠的网页?

I'm trying to use Curl in PHP to read a unreliable web page. The page is often unavailable because of server errors. However, I still need to read it if it's available. Additionally, I don't want the unreliability of the web page to effect my code. I would like my PHP to fail gracefully and move on. Here is what I have so far:

<?php
    function get_url_contents($url){
        $crl = curl_init();
        $timeout = 2;
        curl_setopt ($crl, CURLOPT_URL,$url);
        curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $ret = curl_exec($crl);
        curl_close($crl);
        return $ret;
    }
    $handle = get_url_contents ( 'http://www.mydomain.com/mypage.html' );
?>
  • 写回答

2条回答 默认 最新

  • dongyin2885 2012-06-23 04:09
    关注

    You could test the HTTP code to see if the page was successfully retrieved by testing the HTTP Response code. I can't remember if >200 and <302 are the correct code ranges though, have a quick peak at http response codes If you use this method.

    <?php
        function get_url_contents($url){
            $crl = curl_init();
            $timeout = 2;
            curl_setopt ($crl, CURLOPT_URL,$url);
            curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
            $ret['pagesource'] = curl_exec($crl);
            $httpcode = curl_getinfo($crl, CURLINFO_HTTP_CODE);
            curl_close($crl);
    
            if($httpcode >=200 && $httpcode<302) {
             $ret['response']=true;
            } else {
             $ret['response']=false;
            }
    
            return $ret;
        }
        $handle = get_url_contents ( 'http://192.168.1.118/newTest/mainBoss.php' );
        if($handle['response']==false){
              echo 'page is no good';
        } else {
                 echo 'page is ok and here it is:' . $handle['pagesource'] . 'DONE.<br>';
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用