ylsunyuan技术论坛

标题: CRUL类包括GET和POST [打印本页]

作者: sun    时间: 2015-4-26 17:40
标题: CRUL类包括GET和POST
  1. <?php
  2. /**
  3. *
  4. */
  5. class myCurl
  6. {
  7.        
  8.         function curlGet($url)
  9.         {
  10.                 //$url = "http://apistore.baidu.com/microservice/weather?citypinyin=beijing";
  11.                 //初始化
  12.                 $ch = curl_init();
  13.                 //设置选项,包括URL
  14.                 curl_setopt($ch, CURLOPT_URL, $url);
  15.                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  16.                 curl_setopt($ch, CURLOPT_HEADER, 0);
  17.                 //执行并获取HTML文档内容
  18.                 $result = curl_exec($ch);
  19.                 //释放curl句柄
  20.                 curl_close($ch);
  21.                 //打印获得的数据
  22.                 return $result;
  23.         }

  24.         function curlPost($url,$post_data)
  25.         {
  26.                 //$url = "http://localhost/web_services.php";
  27.                 //$post_data = array ("username" => "bob","key" => "12345");
  28.                 $ch = curl_init();
  29.                 curl_setopt($ch, CURLOPT_URL, $url);
  30.                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  31.                 //post数据
  32.                 curl_setopt($ch, CURLOPT_POST, 1);
  33.                 //post的变量
  34.                 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  35.                 $result = curl_exec($ch);
  36.                 curl_close($ch);
  37.                 //打印获得的数据
  38.                 return $result;
  39.         }

  40. }


  41. $url = "http://apistore.baidu.com/microservice/weather?citypinyin=beijing";
  42. $myCurl = new myCurl();
  43. $res = $myCurl -> curlGet($url);
  44. //echo "<pre>";
  45. //print_r($res);
  46. //echo "</pre>";

  47. $json = json_decode($res,true);
  48. var_dump($json);

  49. echo $json['retData']['city'].$json['retData']['weather']."。气温:".
  50. $json['retData']['temp']."度。风向:".$json['retData']['WD']."风力:".$json['retData']['WS'];

复制代码







欢迎光临 ylsunyuan技术论坛 (http://bbs.ylsunyuan.com/) Powered by Discuz! X3.2