5

私は Slim Framework 2 をまったく使用したことがなく、外部 API への HTTP 呼び出しを行いたいと考えています。

単純に次のようになります。 GET http://website.com/method

Slim を使用してこれを行う方法はありますか、それとも PHP に curl を使用する必要がありますか?

4

3 に答える 3

12

Slim Framework を使用して API を構築できます。他の API を使用するには、PHP Curl を使用できます。

たとえば、次のようになります。

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://website.com/method");
curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result   

// Fetch and return content, save it.
$raw_data = curl_exec($ch);
curl_close($ch);

// If the API is JSON, use json_decode.
$data = json_decode($raw_data);
var_dump($data);

?>
于 2013-04-11T12:37:09.077 に答える
1
<?php
  try {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://website.com/method");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
    curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 2);
    $data = curl_exec($ch);
    if(curl_errno($ch)){
        throw new Exception(curl_error($ch));
    }
    curl_close($ch);
    $data = json_decode($data);
    var_dump($data);
  } catch(Exception $e) {
    // do something on exception
  }
?>
于 2016-02-24T22:17:36.110 に答える