2013-04-11 42 views
3

我对Slim Framework 2完全陌生,我想对外部API进行HTTP调用。Slim框架 - 调用外部API

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

有没有办法做到这一点使用超薄或者我必须使用卷曲的PHP?

回答

8

您可以使用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); 

?> 
+0

感谢。如果没有简单的方法,我会使用它。 – 2013-04-11 12:45:28

0
<?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 
    } 
?> 
+2

请解释一下 – Breek 2016-02-24 22:24:36