我工作了两个小时来解决它,但我需要你们配合。我需要创建一个从db获取的数组。让我们来看看:
$conn_msg_attach = mysql_query("SELECT * FROM task_msg_attach WHERE msg_ID = '$msgID'");
while($get_msg_attach = mysql_fetch_array($conn_msg_attach)) {
$msg_attach_path = $get_msg_attach['msg_filepath'];
$msg_attach_fullpath = '../../../files/task_files/'.$msg_attach_path;
$files = array($msg_attach_path => $msg_attach_fullpath);
}
以上代码我需要做的是:
$files = array(
'something.ttf' => '../../../files/task_files/something.ttf',
'dsc.jpg' => '../../../files/task_files/dsc.jpg',
'hope.pdf' => '../../../files/task_files/hope.pdf'
);
它没有完全正常工作。连接问题:Stackoverflow question file.zip将无效。我找不到问题所在。
我改变了我的观点并写下了代码。但仍然得到错误“ZipArchive :: addFile():无效或未初始化的Zip对象”。噗!
$zipname = 'task.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::OVERWRITE);
$conn_msg_attach = mysql_query("SELECT * FROM task_msg_attach WHERE msg_ID = '$msgID'");
while($get_msg_attach = mysql_fetch_array($conn_msg_attach)) {
$msg_attach_path = $get_msg_attach['msg_filepath'];
$msg_attach_fullpath = '../../../files/task_files/'.$msg_attach_path;
$zip->addFile($msg_attach_fullpath, $msg_attach_path);
}
$zip->close();
感谢您的任何帮助。
问题的最终解决方案:
$msgID = $_GET['msgID'];
$zipname = 'task.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$conn_msg_attach = mysql_query("SELECT * FROM task_msg_attach WHERE msg_ID = '$msgID'");
while($get_msg_attach = mysql_fetch_array($conn_msg_attach)) {
$msg_attach_path = $get_msg_attach['msg_filepath'];
$msg_attach_fullpath = '../../../files/task_files/'.$msg_attach_path;
$zip->addFile($msg_attach_fullpath, $msg_attach_path);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
ob_clean();
readfile($zipname);
ob_flush();
更新后问题已更新
../
但使用absolute file path。$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
你的语法错了:
$files = array($msg_attach_path => $msg_attach_fullpath);
在这里,您要设置每次迭代的值,而不是添加到上次迭代已设置的值。
您希望构建一个名为files
的值数组,每次迭代循环都要向数组添加一行而不是设置一个新数组。所以:
$files[] = array($msg_attach_path => $msg_attach_fullpath);
这会在每次调用时向$files
数组添加一个新行。这也可以改写为:
$files[]['$msg_attach_path'] = $msg_attach_fullpath;
结果:
$ files [0] = array('something.ttf'=>'../../../files/task_files/something.ttf'); $ files [1] = array('dsc.jpg'=>'../../../files/task_files/dsc.jpg'); $ files [2] = array('hope.pdf'=>'../../../files/task_files/hope.pdf'); 等等
(这也可以根据您的确切标准进一步整理和改进)。