由于只是一個小示例,所以過程化簡單寫了,小菜隨便參考,大神大可點解
01 | <?php |
02 | //設置最大執行時間 |
03 | set_time_limit(0); |
04 | function getHtml( $url ){ |
05 | // 1. 初始化 |
06 | $ch = curl_init(); |
07 | // 2. 設置選項,包括URL |
08 | curl_setopt( $ch ,CURLOPT_URL, $url ); |
09 | curl_setopt( $ch ,CURLOPT_RETURNTRANSFER,1); |
10 | curl_setopt( $ch ,CURLOPT_HEADER,0); |
11 | // 3. 執行并獲取HTML文檔內容 |
12 | $output = curl_exec( $ch ); |
13 | if ( $output === FALSE ){ |
14 | $output = '' ; |
15 | } |
16 | // 4. 釋放curl句柄 |
17 | curl_close( $ch ); |
18 | return $output ; |
19 | } |
20 | function getPageData( $url ){ |
21 | // 獲取整個網頁內容 |
22 | $html = getHtml( $url ); |
23 | // 初步獲取主塊內容 |
24 | preg_match( "/教程列表.*教程列表/s" , $html , $body_html ); |
25 | // 返回數據 |
26 | $data = array (); |
27 | //判斷是否存在要獲取的內容 |
28 | if ( count ( $body_html )){ |
29 | // 獲取頁面指定信息 |
30 | preg_match_all( '/<a class="avatar".*user_id="(\S*)" href="(\S*)" rel="external nofollow" /' , $body_html [0], $info_1 ); |
31 | preg_match_all( '/<a href="(.*)" rel="external nofollow" .*title="(.*)"/' , $body_html [0], $info_2 ); |
32 | $info = array_merge ( $info_1 , $info_2 ); |
33 | //組合的信息 |
34 | for ( $index =0; $index < count ( $info [0]); $index ++){ |
35 | //以文章信息作為key存數組,以及覆蓋舊數據 |
36 | $data [ $info [4][ $index ]] = array ( |
37 | 'user_id' => $info [1][ $index ], |
38 | 'user_home' => $info [2][ $index ], |
39 | 'a_url' => $info [4][ $index ], |
40 | 'a_title' => $info [5][ $index ], |
41 | ); |
42 | } |
43 | } |
44 | return $data ; |
45 | } |
46 | header( "Content-type: text/html; charset=utf-8" ); |
47 | echo '<pre>' ; |
48 | // 初始化數據 |
49 | $page_no = 1; |
50 | $data_all = array (); |
51 | // 分頁獲取數據 |
52 | do { |
53 | $url = 'http://www.thinkphp.cn/code/examples/p/' . $page_no ; |
54 | $data = getPageData( $url ); |
55 | $data_all += $data ; |
56 | $page_no ++; |
57 | } while ( $page_no <= 10); //當前只獲取10頁,如果要全部獲取則把條件換成$data或!empty($data) |
58 | var_dump( $data_all ); |
59 | ?> |
接下的入表庫當然就不寫了,那些更小意思了~就此別過吧~
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。