今天我來實例演示一下用php怎樣抓取sina首頁的新聞。 博客文章已經所有遷到這裏了,歡迎訪問! 先貼上個人效果圖: php
如上圖:顯示的是新浪sina首頁的新聞|財經模塊。html
下面介紹個人實現過程。app
用到的函數主要有file_get_contents,preg_match等。函數
過程也很是簡單。spa
<!-- lang: php --> $file=file_get_contents('http://www.sina.com.cn/'); preg_match('/<head>([\s\S]*)<\/head>/',$file,$head); print_r($head[0]); echo '<body><div class="rightbox"><div class="right"> <div class="colpadding"><div id="news" class="md">'; preg_match('/<div id=\"news\" class=\"md\">([\s\S]*) <span id=\"news_con_2\" style=\"display:none;\"><\/span>/',$file,$body); print_r($body[1]); echo '<span id="news_con_2" style="display:none;"></span>'; echo '</div></div></div></div></body></html>';
看到沒有,就是簡單的幾步,就實現了效果。若是對樣式有不滿意的地方,能夠再自行修改。code
總結:htm
博客文章已經所有遷到這裏了,歡迎訪問!blog
1:咱們使用preg_match正則匹配要抓取模塊的div,而後再輸出就好了。圖片
2:這個例子比較簡單,當遇到稍微複雜一點的需求的時候,告訴你們一個調式的好辦法。ci
好比說上面的例子當中你想要看看head部分究竟輸出的是什麼,能夠使用htmlspecialchars函數,來防止轉義:htmlspecialchars($head[0]), 這樣輸出的就是正則匹配的head部分的代碼,方便你的查看和調式。
博客文章已經所有遷到這裏了,歡迎訪問!