CApi.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fec\helpers;
  10. use Yii;
  11. /**
  12. * @author Terry Zhao <2358269014@qq.com>
  13. * @since 1.0
  14. */
  15. class CApi{
  16. # 1.通过函数访问api,获取数据
  17. # JSON格式
  18. /*
  19. 参数说明: $url 为API访问的url
  20. $type 为请求类型,默认为get
  21. $data 为传递的数组数据
  22. $timeout 设置超时时间
  23. 返回值: 返回API返回的数据
  24. */
  25. public static function getCurlData($url,$type="get",$data=array(),$timeout = 10){
  26. //对空格进行转义
  27. $url = str_replace(' ','+',$url);
  28. if($type == "get"){
  29. if(!empty($data) && is_array($data)){
  30. $arr = [];
  31. foreach($data as $k=>$v){
  32. $arr[] = $k."=".$v;
  33. }
  34. $str = implode("&",$arr);
  35. if(strstr($url,"?")){
  36. $url .= "&".$str;
  37. }else{
  38. $url .= "?".$str;
  39. }
  40. }
  41. }
  42. $data = json_encode($data);
  43. $url = urldecode($url);
  44. //echo $url ;exit;
  45. $ch = curl_init();
  46. //设置选项,包括URL
  47. curl_setopt($ch, CURLOPT_URL, "$url");
  48. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  49. curl_setopt($ch, CURLOPT_HEADER, 0);
  50. curl_setopt($ch,CURLOPT_TIMEOUT,$timeout); //定义超时3秒钟
  51. if($type == "post"){
  52. // POST数据
  53. curl_setopt($ch, CURLOPT_POST, 1);
  54. curl_setopt($ch,
  55. CURLOPT_HTTPHEADER,
  56. [
  57. 'Accept: application/json',
  58. 'Content-Type: application/json',
  59. 'Content-Length: ' . strlen($data)
  60. ]
  61. );
  62. // 把post的变量加上
  63. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  64. }
  65. //执行并获取url地址的内容
  66. $output = curl_exec($ch);
  67. //echo $output ;
  68. //释放curl句柄
  69. curl_close($ch);
  70. //var_dump($output);exit;
  71. return $output;
  72. }
  73. }