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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失