PHP调用Linux的命令行执行文件压缩命令_PHP
Jun 01, 2016 pm 12:08 PM
前几天工作中,需要将3个txt文件,打包成*.zip down到本地……
一开始,我和普通青年一样,想到用PHP内置的 ZipArchive,代码看起来应该是这样的:
复制代码 代码如下:
/*拆分成3个txt文件 分别是wow_1.txt wow_2.txt 和 wow_3.txt*/
$zip=new ZipArchive();
$zipfile='./Exl_file/wow.zip';
if($zip->open($zipfile,ZIPARCHIVE::CREATE)===TRUE){
$zip->addFile('./Exl_file/wow_1.txt','wow_1.txt');
$zip->addFile('./Exl_file/wow_2.txt','wow_2.txt');
$zip->addFile('./Exl_file/wow_3.txt','wow_3.txt');
$zip->close();
//下载输出文件后删除相关文件
}else{
echo "ZIP生成失败!";
}
可是纠结的是正式环境上没安装zip扩展,ZipArchive直接没法用,代码绝对比在上面装个扩展要来的快——用PHP调用Linux的命令行 ,执行压缩命令,OK,马上行动!
复制代码 代码如下:
/*拆分成3个txt文件 分别是wow_1.txt wow_2.txt 和 wow_3.txt全部放到 Exl_file 目录下*/
$outputs=array();
/*用php的exec执行Linux命令 括号里的字符串就是你在Linux命令窗口里敲的命令;
第二个参数是linux执行该命令后返回的结果数组;
linux执行返回的每一条结果依次存入该数组
第三个参数是结果,如果执行成功,则Linux返回结果值为0,如果执行失败,则结果值不为0
*/
exec("zip ./Exl_file/wow.zip ./Exl_file/wow_1.txt ./Exl_file/wow_2.txt ./Exl_file/wow_3.txt",$outputs,$rc);
if($rc!=0){
foreach ($outputs as $ko=>$vo){
echo "$vo
";
}
}else{
$zipfile='./Exl_file/wow.zip';
//文件下载输出后删除相关文件
}
}
你可以把if($rc!=0)改成if(1==1)查看Linux执行命令返回的结果行,如下图:
复制代码 代码如下:
adding: Exl_file/wow_1.txt (deflated 96%)
adding: Exl_file/wow_2.txt (deflated 97%)
adding: Exl_file/wow_3.txt (deflated 97%)
可以看到执行返回的信息全部输入到了 $outputs 数组中,*.zip文件生成成功。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to compress files to the smallest size with 7-zip? 7-zip usage tutorial

How to use Go language to compress and decompress files?

How to use PHP to develop a simple file compression function

What should I do if there is no file compression when right-clicking on Win10?

Methods to improve the concurrent performance of Java file compression and decompression

How to parse and filter logs through Linux command line tools?

How to use the gzip module for file compression and decompression in Python 3.x

Solution to the problem of insufficient storage space on C drive
