PHP从网站抓取图片并保存本地的代码

来源:互联网 发布:野外求生手册软件 编辑:程序博客网 时间:2024/04/30 05:42
<?php$ImageUrl = array();$page = 80;$count = 0;do {    $page++;
//用一个动态的url抓取不同页面的图片    $url = "http://photo.hupu.com/nba/new?p=" . $page . "&o=1";    $content = file_get_contents($url);    $reg = "/<img.*?src=\"(.*?)\".*?>/";    preg_match_all($reg, $content, $matches);    $path = '../imgDownload';    if (!file_exists($path)) {        continue;        echo "++++++++++++++++++++++++++++++++++++";    }    for ($i = 0; $i < count($matches[1]); $i++) {        $filename = strrchr($matches[1][$i], '/');        $address = downImage($matches[1][$i], $path . $filename);        $ImageUrl[] = $address;
//这里控制下载图片的数量        if (ImageNumber() == 1002) {            echo "--------------------------------------------------------------";            exit();        }    }} while (true);function ImageNumber(){    $num = 0;    $dirname = '../imgDownload';    $dir_handle = opendir($dirname);    while (readdir($dir_handle)) {        $num++;    }    return $num;}//下载图片的方法function downImage($url, $filename = ""){    if ($url == "")        return false;    if ($filename == "") {        $ext = strrchr($url, ".");        if ($ext != ".gif" && $ext != ".jpg" && $ext != ".png" && $ext != "jpeg")            return false;        $filename = date("YmdHis") . $ext;    }    ob_start();    //make file that output from url goes to buffer    readfile($url);    //file_get_contents($url);  这个方法不行的!!!只能用readfile    $img = ob_get_contents();    ob_end_clean();    $fp = @fopen($filename, "a"); //append    fwrite($fp, $img);    fclose($fp);    return $filename;}

0 0
原创粉丝点击