使用PHP和Curl获取URL内容

时间:2014-02-08 06:02:42

标签: php curl

我正在尝试使用php中的curl库获取url的内容。我写了下面的代码来做这件事。即使我没有在代码中出现错误,输出中也没有打印任何内容。由于没有显示错误消息,我无法弄清楚我做错了什么。我正在尝试打印网址响应的详细信息,例如headers, body, time, size, errors(如果有的话)。我正在使用xampp运行以下代码。

<?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 个答案:

答案 0 :(得分:3)

您的代码运行正常。

只需调用该函数。

echo url_get_contents();

检查Curl是否已打开。

答案 1 :(得分:1)

同意上述答案。另外,如果您在浏览器中运行此操作,则可能需要查看页面的输出源。

相关问题