這陣子因為要做一個與airbnb日曆同步的專案
需求是如何讀取airbnb產生出來的ical url(需要資料是開始時間與結束時間)
例:20170203~20170210
爬文了很多,最後找到相關資訊,稍加修改為以下
ical 來的 url
$ical_url = 'https://www.airbnb.jp/calendar/ical/15875535.ics?s=33084938c04d2536e45bf54783ced030';
這一段是非常重要的解析部份,少了這段file_get_contents會怎麼讀都讀不出個所以然
$ctx = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko')
)
);
這時候file_get_contents下去,print_r 就會看到ical(ics)的資料
$ics = file_get_contents($ical_url,false,$ctx);
再接著下方
$events = explode('END:VEVENT', str_replace("\r", '', $ics));
foreach ($events as $i => $event) {
// 正規表達式去過濾出你要的值
if (preg_match('/DTSTART;\D*(\d+)/m', $event, $start) !== 1 || preg_match('/DTEND;\D*(\d+)/m', $event, $end) != 1) {
continue;
}
//airbnb開始時間
$start_time = strtotime($start[1]);
$start_dates = date('Y,m,d', $start_time);
//airbnb結束時間
$end_time = strtotime($end[1]);
$end_dates = date('Y,m,d', $end_time);
// 最後range_dates 就會是你要的資料了!!
$range_dates[$i] = ['start_time' => $start_dates, 'end_time' => $end_dates];
}
以上打完就可收工了!