How to get PHP ZipArchive to work with variable

北战南征 提交于 2019-12-13 08:35:48

问题


I've been banging my head for a day or two now. The http://php.net/manual/en/ziparchive.extractto.php is pretty straight forward. The problem I have been having is trying to get the

 $zip->open('myFile.zip');

to accept a variable.

 $zip->open($myFile);

I have noticed that in all the examples on the message board and even in the PHP site. The name of the zip file is hard coded in. I have seen one example of a variable being used but I can't get it to work.

 $path = 'zipfile.zip'

 $zip = new ZipArchive;
 if ($zip->open($path) === true) {
  for($i = 0; $i < $zip->numFiles; $i++) {
    $filename = $zip->getNameIndex($i);
    $fileinfo = pathinfo($filename);
    copy("zip://".$path."#".$filename,     "/your/new/destination/".$fileinfo['basename']);
   }                   
   $zip->close();                   
 }

 ?>

The above is the example on the PHP site. My code is similar and is

  $r = "update/".$fileName;
  echo $r;
 $z = new ZipArchive;
    if($z->open('$r') === true){

   $z->extractTo('update/tmp');

   $z->close();
   return 'ok<br>';
   } else {
   return 'Failed';
  }

All standard stuff. But it will only work if I hard code in the file name and location. Has anyone gotten it to work with a variable?

UPDATE: WHAT WORKED

It seems that the whole name cannot be subbed as a variable. But if you sub part of the name it is allowed.

  $r = "myfile";
  $z = new ZipArchive;
 if($z->open("update/".$r.".zip") === true){
      //extractTo($path);
    $z->close();
    print "ok";
  }else{
    print "Failed";
  }

回答1:


You can give the full file path of zip file as a variable also like below. It will work

<?php
  $fileName = "zipfile.zip";
  $r = "ziptest/".$fileName;                //$r = "ziptest/zipfile.zip"; This also accepted.
  echo $r;
 $z = new ZipArchive;
    if($z->open($r) === true){

   $z->extractTo('destination/');

   $z->close();
   print "ok";
   } else {
   print "Failed";
  }
 ?>


来源:https://stackoverflow.com/questions/39565810/how-to-get-php-ziparchive-to-work-with-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!