duanfu5239 2015-04-02 10:52
浏览 273
已采纳

php ziparchive重命名文件为空

I'm using php to create a ziparchive which contains some images. This works fine exept when i try to rename the files. This is the code that works:

$zip_archive->open(tempnam("tmp", "zip"), ZipArchive::OVERWRITE);
foreach ($images as $image) {
  $path = $image['path'];
  $title = $image['title'];
  if(file_exists($path)){
    $zip_file->addFile($path, pathinfo($path, PATHINFO_BASENAME));
  }
}
$zip_archive->close();

$images is an array and could look like this:

$images = array(
    'path' => array(
        'folder/title1.jpg',
        'folder/title2.jpg'
    ),
    'title' => array(
        'new_name1.jpg',
        'new_name2.jpg'
    )
)

I would like to name the image as its title.

$zip_file->addFile($path, $title);

But whats happening is that the files in the zip with the title as name are empty. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • doswy02440 2015-04-02 14:43
    关注

    If I run this

    $images = array(
        'path' => array(
            'folder/title1.jpg',
            'folder/title2.jpg'
        ),
        'title' => array(
            'new_name1.jpg',
            'new_name2.jpg'
        )
    );
    
    $i = 0;
    foreach($images as $image)
        var_dump($image, $i++);
    

    I get

    array(2) {
      [0]=>
      string(17) "folder/title1.jpg"
      [1]=>
      string(17) "folder/title2.jpg"
    }
    int(0)
    array(2) {
      [0]=>
      string(13) "new_name1.jpg"
      [1]=>
      string(13) "new_name2.jpg"
    }
    int(1)
    

    This means that these

    $path = $image['path'];
    $title = $image['title'];
    

    are both NULL

    You have two ways to fix this:

    • Change the array to look like

      $images = array(
          [0] => array(
              'path' => 'folder/title1.jpg',
              'title' => 'new_name1.jpg'
          ),
          [1] => array(
              'path' => 'folder/title2.jpg'
              'title' => 'new_name2.jpg',
          )
      );
      

      in this case your initial code should work

    • Change the way to access the array, doing something like

      for($i = 0;$i < count($images['path']);$i++)
      {
          $path = $image['path'][$i];
          $title = $image['title'][$i];
      }
      

      This way you are sure that path and title of the image will have the same index, but it's not recommanded to do so because the array must be ordered.

    I suggest you to change the array, your code should be ok that way

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多