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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?