PHP中採集網頁信息的幾種方式

第一種,經過file_get_contents()函數獲取網頁內容,使用此方法,需在PHP的配置文件php.ini中將allow_url_fopen = On,user_agent="PHP",如若會產生錯誤,可經過ini_set()設置代理,或直接在配置文件中修改。此外還有一種隱蔽的錯誤,並非你本身代碼的問題,如你要獲取20張圖片,可是PHP報錯「HTTP request failed! HTTP/1.1 404 Not Found」,數量爲3次,此時是網站上沒有相應的資源,在file_get_contents()函數前加錯誤抑制符「@」便可!@file_get_contents($val); 示例代碼:php

foreach($temp[2] as $key=>$val){
				$fileName = './public/img/'.time().'-'.rand(1000, 9999).'.jpg';

				ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)'); 
				$img = @file_get_contents($val);
				file_put_contents($fileName, $img);
			}
相關文章
相關標籤/搜索