如何在 PHP 中使用 cURL 获得响应 [英] How to get response using cURL in PHP

查看:32
本文介绍了如何在 PHP 中使用 cURL 获得响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个独立的 PHP 类,我想要一个通过 cURL 调用 API 并获取响应的函数.有人可以帮助我吗?

谢谢.

解决方案

只要使用下面的一段代码就可以得到来自 restful web service url 的响应,我使用的是社交提及 url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");$resArr = 数组();$resArr = json_decode($response);echo "

";打印_r($resArr);echo "</pre>";函数 get_web_page($url) {$options = 数组(CURLOPT_RETURNTRANSFER =>true,//返回网页CURLOPT_HEADER =>false,//不返回标题CURLOPT_FOLLOWLOCATION =>true,//跟随重定向CURLOPT_MAXREDIRS =>10,//重定向 10 次后停止CURLOPT_ENCODING =>"",//处理压缩CURLOPT_USERAGENT =>"test",//客户端名称CURLOPT_AUTOREFERER =>true,//在重定向时设置引用CURLOPT_CONNECTTIMEOUT =>120,//连接超时CURLOPT_TIMEOUT =>120,//响应超时);$ch = curl_init($url);curl_setopt_array($ch, $options);$content = curl_exec($ch);curl_close($ch);返回 $content;}

I want to have a standalone PHP class where I want to have a function which calls an API through cURL and gets the response. Can someone help me in this?

Thanks.

解决方案

Just use the below piece of code to get the response from restful web service url, I use social mention url.

$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";

function get_web_page($url) {
    $options = array(
        CURLOPT_RETURNTRANSFER => true,   // return web page
        CURLOPT_HEADER         => false,  // don't return headers
        CURLOPT_FOLLOWLOCATION => true,   // follow redirects
        CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
        CURLOPT_ENCODING       => "",     // handle compressed
        CURLOPT_USERAGENT      => "test", // name of client
        CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
        CURLOPT_TIMEOUT        => 120,    // time-out on response
    ); 

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);

    $content  = curl_exec($ch);

    curl_close($ch);

    return $content;
}

这篇关于如何在 PHP 中使用 cURL 获得响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆