如何在PHP中使用cURL获得响应

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

谢谢。

只需使用下面的一段代码来获得来自宁静的web服务url的响应,我使用社交提及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; } 

解决的症结在于设定

 CURLOPT_RETURNTRANSFER => true 

然后

 $response = curl_exec($ch); 

CURLOPT_RETURNTRANSFER告诉PHP将响应存储在variables中,而不是将其打印到页面,所以$ response将包含您的响应。 这是你最基本的工作代码(我想,没有testing):

 // init curl object $ch = curl_init(); // define options $optArray = array( CURLOPT_URL => 'http://www.google.com', CURLOPT_RETURNTRANSFER => true ); // apply those options curl_setopt_array($ch, $optArray); // execute request and get response $result = curl_exec($ch); 

如果有其他人遇到这个问题,我会添加另一个答案来提供响应代码或“响应”中可能需要的其他信息。

http://php.net/manual/en/function.curl-getinfo.php

 // init curl object $ch = curl_init(); // define options $optArray = array( CURLOPT_URL => 'http://www.google.com', CURLOPT_RETURNTRANSFER => true ); // apply those options curl_setopt_array($ch, $optArray); // execute request and get response $result = curl_exec($ch); // also get the error and response code $errors = curl_error($ch); $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); var_dump($errors); var_dump($response); // output string(0) "" int(200) // change www.google.com to www.googlebofus.co string(42) "Could not resolve host: www.googlebofus.co" int(0)