5

I'm completely new to Slim Framework 2 and I would like to make an HTTP call to an external API.

It would simply something like: GET http://website.com/method

Is there a way to do this using Slim or do I have to use curl for PHP?

3 Answers 3

12

You can build an API using Slim Framework. To consume other API, you can use PHP Curl.

So for example:

<?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);

?>
1
  • Thanks. I'll use this if there is no simpler way. Apr 11, 2013 at 12:45
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
  }
?>
1
  • 2
    please explain a bit
    – Breek
    Feb 24, 2016 at 22:24
0

I prefer using file_get_contents which is able to fetch remote files and can be tuned using the $context argument. The fourth example shows a get request.

$file = file_get_contents('http://www.example.com/', false, $context);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.