dtwbp26022 2014-02-08 06:02
浏览 131

使用PHP和Curl获取URL内容

I am trying to fetch contents of a url using the curl library in php. I have written the below code to do this. Even though I'am not getting an error in the code, nothing is being printed in the output. As there is no error message being displayed, I'm not able to figure out what I'm doing wrong. I'm trying to print details of url response like headers, body, time, size, errors (if any). I'm using xampp to run the below code.

<?php
    function url_get_contents($url="google.com",$useragent='cURL',$headers=false,
    $follow_redirects=false,$debug=false) {

        # initialise the CURL library
        $ch = curl_init();

        # specify the URL to be retrieved
        curl_setopt($ch, CURLOPT_URL,$url);

        # we want to get the contents of the URL and store it in a variable
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

        # specify the useragent: this is a required courtesy to site owners
        curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

        # ignore SSL errors
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        # return headers as requested
        if ($headers==true){
            curl_setopt($ch, CURLOPT_HEADER,1);
        }

        # only return headers
        if ($headers=='headers only') {
            curl_setopt($ch, CURLOPT_NOBODY ,1);
        }

        # follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
        if ($follow_redirects==true) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }

        # if debugging, return an array with CURL's debug info and the URL contents
        if ($debug==true) {
            $result['contents']=curl_exec($ch);
            $result['info']=curl_getinfo($ch);
        }

        # otherwise just return the contents as a variable
        else $result=curl_exec($ch);

        # free resources
        curl_close($ch);

        # send back the data
        return $result;
    }
?> 
  • 写回答

2条回答 默认 最新

  • dongzhao4036 2014-02-08 06:13
    关注

    Your code is working perfectly.

    Just call the function.

    echo url_get_contents();
    

    Check whether Curl is switched ON.

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示