PHP实战:guzzlehttp/guzzle下载网络文件到本地

环境

$ php -v
PHP 7.1.23 

依赖

composer require "guzzlehttp/guzzle=6.5"
composer require "ramsey/uuid=3.9"

示例

<?php

require_once './vendor/autoload.php';

use GuzzleHttp\Client;
use Ramsey\Uuid\Uuid;

/**
 * 递归创建文件夹
 * @param $dir
 */
function safeMakeDir($dir)
{
    
    
    if (!file_exists($dir)) {
    
    
        mkdir($dir, 0777, true);
    }
}

/**
 * 随机获取字符串
 * @return string
 * @throws Exception
 */
function getRandomString()
{
    
    
    return Uuid::uuid4()->toString();
}

/**
 * 获取文件扩展名
 * @param $filename
 * @return mixed
 */
function getFileNameExtension($filename)
{
    
    
    return array_slice(explode('.', $filename), -1)[0];
}

/**
 * 获取文件内容
 * @param $url
 * @return string
 */
function getUrlContent($url)
{
    
    

    $client   = new Client();
    $response = $client->get($url);

    $body = $response->getBody();

    return $body->getContents();
}

/**
 * 保存到本地
 * @param $url
 * @param $dir
 * @throws Exception
 */
function saveUrlToLocalFile($url, $dir)
{
    
    
    safeMakeDir($dir);

    $ext  = getFileNameExtension($url);
    $uuid = getRandomString();

    $filename = "{
      
      $dir}/{
      
      $uuid}.{
      
      $ext}";

    $content = getUrlContent($url);

    file_put_contents($filename, $content);

}

function main()
{
    
    
    $url = 'https://cn.bing.com/th?id=OHR.WartburgCastle_ZH-CN4201605751_1920x1080.jpg&rf=LaDigue_1920x1080.jpg';
    $dir = 'temp';

    saveUrlToLocalFile($url, $dir);
}

main();

文件保存到了:

temp/113380ed-bf1b-40cf-8b19-5aefcb66fc17.jpg

猜你喜欢

转载自blog.csdn.net/mouday/article/details/127426597
今日推荐