自学的菜鸟
2021-11-26 17:13
采纳率: 59.3%
浏览 43
已结题

php怎么下载图片到本地,指定路径,指定文件名

$array = ['https://gd1.alicdn.com/imgextra/i2/797209094/O1CN01YcjYtK2H36XstzLpR_!!797209094.jpg',
'https://gd2.alicdn.com/imgextra/i2/797209094/O1CN01KbwQNL2H36Xn1KTZW_!!797209094.jpg',
'https://gd1.alicdn.com/imgextra/i1/797209094/O1CN01FAxHAG2H36Xn50KiP_!!797209094.jpg',
'https://gd1.alicdn.com/imgextra/i1/797209094/O1CN01oD1dIu2H36XqDE6o4_!!797209094.jpg',
'https://gd3.alicdn.com/imgextra/i3/797209094/O1CN01mLHgwZ2H36XnihHWp_!!797209094.jpg']

怎么遍历这个数组,并下载图片到本地,我的php文件在这个路径下'/www/wwwroot/sale/php/',我想把图片下载到这个路径‘'/www/wwwroot/sale/image/'’,
指定文件名i.jpg,有没有人能帮我写下,谢谢

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • 代码的灵魂是bug! 2021-11-26 17:22
    最佳回答

    images文件夹需要提前创建

    <?php
    
    $images = ['https://gd1.alicdn.com/imgextra/i2/797209094/O1CN01YcjYtK2H36XstzLpR_!!797209094.jpg',
    'https://gd2.alicdn.com/imgextra/i2/797209094/O1CN01KbwQNL2H36Xn1KTZW_!!797209094.jpg',
    'https://gd1.alicdn.com/imgextra/i1/797209094/O1CN01FAxHAG2H36Xn50KiP_!!797209094.jpg',
    'https://gd1.alicdn.com/imgextra/i1/797209094/O1CN01oD1dIu2H36XqDE6o4_!!797209094.jpg',
    'https://gd3.alicdn.com/imgextra/i3/797209094/O1CN01mLHgwZ2H36XnihHWp_!!797209094.jpg'];
    
    function download($url, $path = 'images/')
    {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
      $file = curl_exec($ch);
      curl_close($ch);
      $filename = pathinfo($url, PATHINFO_BASENAME);
      $resource = fopen($path . $filename, 'a');
      fwrite($resource, $file);
      fclose($resource);
    }
    
    
    foreach ( $images as $url ) {
      download($url);
    }
    
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题