我完全不了解Slim Framework 2,我想向外部API发起HTTP调用。
它大概是这样的:GET http://website.com/method
是否有一种使用Slim的方法来实现这个功能,还是我必须使用PHP的curl?
您可以使用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);
?>
<?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
}
?>
我更喜欢使用 file_get_contents,它可以获取远程文件并可通过 $context
参数进行调整。第四个示例 显示了一个 get 请求。
$file = file_get_contents('http://www.example.com/', false, $context);