Test.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. ]);
  28. // 使用 POSTFIELDS 设置 GET 参数
  29. curl_setopt($ch, CURLOPT_HTTPGET, true); // 让 cURL 知道这是一个 GET 请求
  30. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); // 设置 GET 参数
  31. // 执行 cURL 请求
  32. $response = curl_exec($ch);
  33. // 检查请求是否成功
  34. if (curl_errno($ch)) {
  35. echo 'cURL error: ' . curl_error($ch);
  36. exit;
  37. }
  38. // 关闭 cURL 会话
  39. curl_close($ch);
  40. // 处理响应
  41. return json_decode($response, true);
  42. }
  43. }