通過(guò)一個(gè)簡(jiǎn)單的例子復(fù)習(xí)一下幾個(gè)php函數(shù)的用法
用到的函數(shù)或知識(shí)點(diǎn)curl 發(fā)送網(wǎng)絡(luò)請(qǐng)求
preg_match 正則匹配
代碼$url = http://desk.zol.com.cn/bizhi/7386_91671_2.html $headers = [ user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 $ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //將curl_exec()獲取的信息以字符串返回,而不是直接輸出。curl_setopt($ch, CURLOPT_HEADER, $headers);$output = curl_exec($ch);curl_close($ch);$str = mb_convert_encoding($output, utf-8 , gb2312 //或$str = iconv( gb2312//IGNORE , utf-8 , $output);preg_match( ! img id= bigImg src= (? src http.*/.(? ext jpg|png)) .* ! , $str, $m);file_put_contents( ./meinv. . $m[ ext ], file_get_contents($m[ src ]));效果
在php中建立curl連接的步驟一般為:初始化,設(shè)置選項(xiàng),執(zhí)行操作,釋放連接。
$ch = curl_init();curl_setopt($ch, CURLOPT, $opt);$out = curl_exec($ch);curl_close();
常用的CURLOPT設(shè)置,更多參考文檔 http://php.net/manual/zh/function.curl-setopt.php
CURLOPT_URL, string //設(shè)置url必須CURLOPT_HEADER, array //設(shè)置請(qǐng)求headerCURLOPT_RETURNTRANSFER, bool //為true時(shí),以字符串返回響應(yīng),不包含headerCURLOPT_SSL_VERIFYPEER, bool //為false時(shí),不驗(yàn)證https證書,用于請(qǐng)求https的urlCURLOPT_POST, int //為1時(shí)配合CURLOPT_POSTFIELDS使用post請(qǐng)求,默認(rèn)使用getCURLOPT_POSTFIELDS, array //post數(shù)據(jù)數(shù)組
直接輸出$output發(fā)現(xiàn)亂碼,通過(guò)查看源碼發(fā)現(xiàn)網(wǎng)頁(yè)使用的是gb2312編碼,用mb_convert_encoding或者iconv轉(zhuǎn)換成utf-8編碼輸出。
preg_match 正則匹配
通過(guò)查看源碼發(fā)現(xiàn)我們需要的圖片標(biāo)簽為 img id= bigImg src= /uploads/allimg/190427/1011191627-2.jpg width= 960 height= 600
img id= bigImg src= (? src http.*/.(? ext jpg|png)) .*
.*匹配所有,(? name )使用分組可以方便的使用$match[ name ]取到想要的部分
最后$match[ src ]拿到了圖片的真實(shí)url,通過(guò)file_put_contents保存,就算完成了
以上就是php爬取圖片并保存到本地的代碼示例的詳細(xì)內(nèi)容,PHP教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選