Home Backend Development PHP Tutorial PHP remotely grabs website images and saves them

PHP remotely grabs website images and saves them

Mar 29, 2018 pm 04:22 PM
php keep picture

This article shares with you the code for PHP to capture website images and save them. This example introduces in detail the method of capturing images and saving them locally. Friends in need can refer to it

Example, PHP code to capture website data.

Code example:

<?php  
/** 
 * 一个用于抓取图片的类 
 * 
 * @package default 
 * @author  WuJunwei 
 */  
class download_image   
{  
      
    public $save_path;  //抓取图片的保存地址  
  
    //抓取图片的大小限制(单位:字节) 只抓比size比这个限制大的图片  
    public $img_size=0;   
  
    //定义一个静态数组,用于记录曾经抓取过的的超链接地址,避免重复抓取         
    public static $a_url_arr=array();     
      
    /** 
     * @param String $save_path    抓取图片的保存地址 
     * @param Int    $img_size     抓取图片的保存地址 
     */  
    public function __construct($save_path,$img_size)  
    {  
        $this->save_path=$save_path;  
        $this->img_size=$img_size;  
    }      
      
    /** 
     * 递归下载抓取首页及其子页面图片的方法  ( recursive 递归) 
     * 
     * @param   String  $capture_url  用于抓取图片的网址 
     *  
     */  
    public function recursive_download_images($capture_url)  
    {  
        if (!in_array($capture_url,self::$a_url_arr))   //没抓取过  
        {                           
            self::$a_url_arr[]=$capture_url;   //计入静态数组  
        } else   //抓取过,直接退出函数  
        {  
            return;  
        }          
          
        $this->download_current_page_images($capture_url);  //下载当前页面的所有图片  
          
        //用@屏蔽掉因为抓取地址无法读取导致的warning错误  
        $content=@file_get_contents($capture_url);   
          
        //匹配a标签href属性中?之前部分的正则  
        $a_pattern = "|<a[^>]+href=[&#39;\" ]?([^ &#39;\"?]+)[&#39;\" >]|U";     
        preg_match_all($a_pattern, $content, $a_out, PREG_SET_ORDER);  
          
        $tmp_arr=array();  //定义一个数组,用于存放当前循环下抓取图片的超链接地址  
        foreach ($a_out as $k => $v)   
        {  
            /** 
             * 去除超链接中的 空&#39;&#39;,&#39;#&#39;,&#39;/&#39;和重复值   
             * 1: 超链接地址的值 不能等于当前抓取页面的url, 否则会陷入死循环 
             * 2: 超链接为&#39;&#39;或&#39;#&#39;,&#39;/&#39;也是本页面,这样也会陷入死循环,   
             * 3: 有时一个超连接地址在一个网页中会重复出现多次,如果不去除,会对一个子页面进行重复下载) 
             */  
            if ( $v[1] && !in_array($v[1],self::$a_url_arr) &&!in_array($v[1],array(&#39;#&#39;,&#39;/&#39;,$capture_url) ) )   
            {  
                $tmp_arr[]=$v[1];  
            }  
        }  
    
        foreach ($tmp_arr as $k => $v)   
        {              
            //超链接路径地址  
            if ( strpos($v, &#39;http://&#39;)!==false ) //如果url包含http://,可以直接访问  
            {  
                $a_url = $v;  
            }else   //否则证明是相对地址, 需要重新拼凑超链接的访问地址  
            {  
                $domain_url = substr($capture_url, 0,strpos($capture_url, &#39;/&#39;,8)+1);  
                $a_url=$domain_url.$v;  
            }  
  
            $this->recursive_download_images($a_url);  
  
        } 
    }   
    /** 
     * 下载当前网页下的所有图片  
     * 
     * @param   String  $capture_url  用于抓取图片的网页地址 
     * @return  Array   当前网页上所有图片img标签url地址的一个数组 
     */  
    public function download_current_page_images($capture_url)  
    {  
        $content=@file_get_contents($capture_url);   //屏蔽warning错误  
  
        //匹配img标签src属性中?之前部分的正则  
        $img_pattern = "|<img[^>]+src=[&#39;\" ]?([^ &#39;\"?]+)[&#39;\" >]|U";     
        preg_match_all($img_pattern, $content, $img_out, PREG_SET_ORDER);  
  
        $photo_num = count($img_out);  
        //匹配到的图片数量  
        echo &#39;<h1>&#39;.$capture_url . "共找到 " . $photo_num . " 张图片</h1>";  
        foreach ($img_out as $k => $v)   
        {  
            $this->save_one_img($capture_url,$v[1]);  
        }  
    }
  
    /** 
     * 保存单个图片的方法  
     * 
     * @param String $capture_url   用于抓取图片的网页地址 
     * @param String $img_url       需要保存的图片的url 
     *  
     */  
    public function save_one_img($capture_url,$img_url)  
    {          
        //图片路径地址  
        if ( strpos($img_url, &#39;http://&#39;)!==false )   
        {  
            // $img_url = $img_url;  
        }else     
        {  
            $domain_url = substr($capture_url, 0,strpos($capture_url, &#39;/&#39;,8)+1);  
            $img_url=$domain_url.$img_url;  
        }             
        $pathinfo = pathinfo($img_url);    //获取图片路径信息          
        $pic_name=$pathinfo[&#39;basename&#39;];   //获取图片的名字  
        if (file_exists($this->save_path.$pic_name))  //如果图片存在,证明已经被抓取过,退出函数  
        {  
            echo $img_url . &#39;<span style="color:red;margin-left:80px">该图片已经抓取过!</span><br/>&#39;;   
            return;  
        }                  
        //将图片内容读入一个字符串  
        $img_data = @file_get_contents($img_url);   //屏蔽掉因为图片地址无法读取导致的warning错误  
        if ( strlen($img_data) > $this->img_size )   //下载size比限制大的图片  
        {  
            $img_size = file_put_contents($this->save_path . $pic_name, $img_data);  
            if ($img_size)  
            {  
                echo $img_url . &#39;<span style="color:green;margin-left:80px">图片保存成功!</span><br/>&#39;;  
            } else  
            {  
                echo $img_url . &#39;<span style="color:red;margin-left:80px">图片保存失败!</span><br/>&#39;;  
            }  
        } else  
        {  
            echo $img_url . &#39;<span style="color:red;margin-left:80px">图片读取失败!</span><br/>&#39;;  
        }   
    }   
} // END  
  
set_time_limit(120);     //设置脚本的最大执行时间  根据情况设置   
$download_img=new download_image(&#39;E:/images/&#39;,0);   //实例化下载图片对象  
$download_img->recursive_download_images(&#39;http://www.jbxue.com/&#39;); //递归抓取图片方法  
//$download_img->download_current_page_images($_POST[&#39;capture_url&#39;]); //只抓取当前页面图片方法  
?>
Copy after login

Related recommendations:

Grab pictures from a website and automatically download them to a folder

Specific implementation method of capturing images in PHP_PHP tutorial

Using PHP’s Snoopy class to capture images_PHP tutorial

The above is the detailed content of PHP remotely grabs website images and saves them. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles