2017-08-14 82 views
0

我是PhP的新手,嘗試使用curl向第三方API發出請求。這是我正在嘗試的,但它只是響應API的根端點上的內容。PHP中的捲曲API調用

$service_url = 'http://api.kivaws.org/graphql'; 
$curl = curl_init($service_url); 
$curl_post_data = array(
     'Pragma' => 'no-cache', 
     'Origin' => 'http://api.kivaws.org', 
     'Accept-Encoding' => 'gzip, deflate', 
     'Accept-Language' => 'en-US,en;q=0.8', 
     'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', 
     'content-type' => 'application/json', 
     'accept' => 'application/json', 
     'Cache-Control' => 'no-cache', 
     'Connection' => 'keep-alive', 
     'data' => '{"query":"{ 
      loans (filters: {gender: male, status:funded, country: [\"KE\", \"US\"]}, sortBy: newest, limit: 2) { 
      totalCount 
      values { 
       name 
       status 
       loanAmount 
      } 
      } 
     }","variables":null,"operationName":null}' 
); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); 
$curl_response = curl_exec($curl); 
if ($curl_response === false) { 
    $info = curl_getinfo($curl); 
    curl_close($curl); 
    die('error occured during curl exec. Additioanl info: ' . var_export($info)); 
} 
curl_close($curl); 

echo $curl_response; 
+0

你能請張貼的內容是終點回應? –

+0

你想要什麼樣的輸出? –

+0

hello @Brett我從你的Api curl得到了這個響應,這是正確的嗎? ** {「data」:{「hello」:「歡迎來到Kiva的GraphQL API!」}} ** –

回答

0

這似乎是在做的伎倆:利用curl_setopt設置一些重要的東西,比如CURLOPT_HTTPHEADERCURLOPT_RETURNTRANSFERTrue這樣它會返回我們在體內的結果,然後使用編碼的json_encode查詢。

$service_url = 'http://api.kivaws.org/graphql'; 

$curl = curl_init($service_url); 

$curl_post_data = array("query" => '{loans (filters: {gender: male, status:funded, country: ["KE", "US"]}, sortBy: newest, limit: 2) {totalCount values { name status loanAmount }}}'); 
$data_string = json_encode($curl_post_data); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json', 
    'Content-Length: ' . strlen($data_string)) 
); 

$curl_response = curl_exec($curl); 
if ($curl_response === false) { 
    $info = curl_getinfo($curl); 
    curl_close($curl); 
    die('error occured during curl exec. Additioanl info: ' . var_export($info)); 
} 
curl_close($curl); 
echo $curl_response; 
echo $info; 

這將返回我:

{"data":{"loans":{"totalCount":40425,"values":[{"name":"Davis","status":"funded","loanAmount":"100.00"},{"name":"James","status":"funded","loanAmount":"100.00"}]}}} 
+0

真棒。萬分感謝。 – Brett