Test.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. class Test extends Controller
  5. {
  6. public function index()
  7. {
  8. $data = $this->football();
  9. return $this->success($data);
  10. }
  11. function football()
  12. {
  13. $url = 'https://v3.football.api-sports.io/teams';
  14. // GET 参数
  15. $params = [
  16. 'id' => 33
  17. ];
  18. // 设置 HTTP 请求的上下文
  19. $key = env("API_FOOTBALL_KEY", '');
  20. // 初始化 cURL 会话
  21. $ch = curl_init();
  22. // 设置 cURL 选项
  23. curl_setopt($ch, CURLOPT_URL, $url); // 不用拼接查询字符串
  24. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  25. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  26. "x-rapidapi-key: {$key}",
  27. "Accept: application/json",
  28. "User-Agent: PHP"
  29. ]);
  30. // 使用 POSTFIELDS 设置 GET 参数
  31. curl_setopt($ch, CURLOPT_HTTPGET, true); // 让 cURL 知道这是一个 GET 请求
  32. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); // 设置 GET 参数
  33. // 执行 cURL 请求
  34. $response = curl_exec($ch);
  35. // 检查请求是否成功
  36. if (curl_errno($ch)) {
  37. echo 'cURL error: ' . curl_error($ch);
  38. exit;
  39. }
  40. // 关闭 cURL 会话
  41. curl_close($ch);
  42. // 处理响应
  43. return json_decode($response, true);
  44. }
  45. }