【问题标题】:Slim framework - Call external APISlim 框架 - 调用外部 API
【发布时间】:2013-04-03 15:43:48
【问题描述】:

我是 Slim Framework 2 的新手,我想对外部 API 进行 HTTP 调用。

它只是这样的: GET http://website.com/method

有没有办法使用 Slim 来做到这一点,还是我必须在 PHP 中使用 curl?

【问题讨论】:

    标签: api rest curl slim


    【解决方案1】:

    我更喜欢使用file_get_contents,它能够获取远程文件并且可以使用$context 参数进行调整。 fourth example 显示一个获取请求。

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

    【讨论】:

      【解决方案2】:
      <?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
        }
      ?>
      

      【讨论】:

      • 请解释一下
      【解决方案3】:

      您可以使用 Slim 框架构建 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);
      
      ?>
      

      【讨论】:

      • 谢谢。如果没有更简单的方法,我会使用它。
      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2015-12-14
      相关资源
      最近更新 更多