2011-06-29 42 views

回答

82

只是用下面一段代碼從RESTful Web服務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; 
} 
+5

過時的歌曲的bug一個禮包... +1使用curl_setopt_array()。比反覆調用curl_setopt()更清潔。 – Ligemer

52

解決方案的核心是設定

CURLOPT_RETURNTRANSFER => true 

然後

$response = curl_exec($ch); 

CURLOPT_RETURNTRANSFER告訴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); 
+3

給點答案。解決了我的問題。非常感謝你。 –

+1

很好的解釋。 – Kailas

12

如果任何人遇到這樣,我加入另一個答案提供可能在需要響應代碼或其他信息響應」。

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) 
+0

不錯,我不知道curl_error() – siliconrockstar