|
1 <?php
2
3 /**
4 * author: NickBai
5 * createTime: 2016/12/26 0026 上午 9:11
6 *
7 */
8>
9 {
10 public $fromStation = null;
11 public $toStation = null;
12 public $date = null;
13
14 public function __construct($fromStation = null, $toStation = null, $date = null)
15 {
16 if (!file_exists(ROOT_PATH . '/data/station.json')) {
17 $this->parseStation();
18 }
19
20 $this->fromStation = $fromStation;
21 $this->toStation = $toStation;
22 $this->date = $date;
23 }
24
25 /**
26 * 入口函数
27 */
28 public function run()
29 {
30 if (is_null($this->fromStation) || is_null($this->toStation))
31 throw new Exception('起始站不能为空!');
32 is_null($this->date) && $date = date('Y-m-d');
33
34 $url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=' . $this->date . '&from_station=';
35 $url .= $this->fromStation . '&to_station=' . $this->toStation;
36
37 $ticketInfo = $this->curlGet($url);
38 return $ticketInfo;
39 }
40
41 /**
42 * 解析火车站信息
43 */
44 private function parseStation()
45 {
46 $url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8992';
47 $station = $this->curlGet($url, false);
48
49 if (empty($station)) {
50 throw new Exception('获取站点信息失败!');
51 }
52
53 $delStr = "var station_names ='"; //需要截断的字符
54 $station = substr($station, strlen($delStr), strlen($station));
55
56 $station = explode('@', $station);
57 $json = [
58 'message' => ''
59 ];
60
61 foreach ($station as $key => $vo) {
62 if (empty($vo)) continue;
63
64 $st = explode('|', $vo);
65 $json['value'][] = [
66 'stationName' => $st['1'],
67 'shortName' => $st['3'],
68 'stationFlag' => $st['2']
69 ];
70 }
71 unset($station);
72
73 file_put_contents(ROOT_PATH . '/data/station.json', json_encode($json));
74 }
75
76 /**
77 * 采集数据
78 * @param $url
79 * @param $decode
80 */
81 private function curlGet($url, $decode = true)
82 {
83 $ch = curl_init();
84 $timeout = 5;
85 $header = [
86 'Accept:*/*',
87 'Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3',
88 'Accept-Encoding:gzip,deflate,sdch',
89 'Accept-Language:zh-CN,zh;q=0.8,ja;q=0.6,en;q=0.4',
90 'Connection:keep-alive',
91 'Host:kyfw.12306.cn',
92 'Referer:https://kyfw.12306.cn/otn/lcxxcx/init',
93 ];
94 curl_setopt($ch, CURLOPT_URL, $url);
95 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
96 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
97 curl_setopt($ch, CURLOPT_ENCODING, "gzip"); //指定gzip压缩
98 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
99 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
100 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
101 $result = curl_exec($ch);
102 curl_close($ch);
103
104 $decode && $result = json_decode($result, true);
105
106 return $result;
107 }
108
109 } |
|
|