我正试图从wordpress中的post附件创建一个zip文件。
我尝试了下面的两种方法,但都没有结果(没有错误消息,没有创建文件)-我做错了什么(再次..)
我不认为那些是wordpress中的帖子附件的事实与此有任何关系,因为这些方法在普通文件中也失败了。为什么-->看看答案。
$files_to_zip = array();// create files array
//run a query
$post_id = get_the_id();
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$files_to_zip [] = wp_get_attachment_url( $attachment->ID ); // populate files array
}
}
print_r($files_to_zip);
$zip = new ZipArchive;
$zip->open('file.zip', ZipArchive::CREATE);
foreach ($files_to_zip as $file) {
$zip->addFile($file);
}
$zip->close();
还有这种方法:
$files_to_zip = array(); // create array
//run a query
$post_id = get_the_id();
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post_id
);
$zip = new ZipArchive;
$zip->open('file.zip', ZipArchive::CREATE);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$zip->addFile(wp_get_attachment_url( $attachment->ID ));
}
}
print_r($files_to_zip);// debug - return file names OK
$zip->close();
两个方法都没有返回任何结果。。任何见解都将不胜感激。
编辑I-阵列$files_to_zip 的示例打印_r
print_r($files_to_zip);
Array (
[0] => http://localhost/testing_evn/wp-content/uploads/2012/03/wrt-62316IMAG0659.jpg
[2] => http://localhost/testing_evn/wp-content/uploads/2012/03/wrt-85520_IGP0255.jpg
[3] => http://localhost/testing_evn/wp-content/uploads/2012/03/wrt-85520_IZTP0635.jpg
[4] => http://localhost/testing_evn/wp-content/uploads/2012/03/wrt-85520_ITG035t5.jpg
[5] => http://localhost/testing_evn/wp-content/uploads/2012/03/wrt-85520_IRTT7375.jpg )
通过使用get_attached_file(),它将生成real路径(在某个时候,我怀疑php可能无法通过HTTP创建zip,这是简短的答案。请参阅下面的长路径。)
好的-我会在这里回答我自己的问题。。
我已经证实了我自己的怀疑——PHP在通过HTTP传递时无法创建ZIP——所以我们需要一个PATH,而不是URL。。。
因此,例如在Wordpress的情况下,需要使用get_attached_file()来生成真实路径。。
Array (
[0] => C:Documents and SettingsOBhtdocstest_envwp-contentuploads2012 3wrt-62316IMAG0659.jpg
[2] => C:Documents and SettingsOBhtdocstest_envwp-contentuploads2012 3wrt-85520_IGP0255.jpg
[3] => C:Documents and SettingsOBhtdocstest_envwp-contentuploads2012 3wrt-85520_IZTP0635.jpg
[4] => C:Documents and SettingsOBhtdocstest_envwp-contentuploads2012 3wrt-85520_ITG035t5.jpg
[5] => C:Documents and SettingsOBhtdocstest_envwp-contentuploads2012 3wrt-85520_IRTT7375.jpg )
(感谢@DaveRandom对看到var_dump数组的评论——实际上我已经看了很多次了,但直到有人特别要求看它,我才太注意。)
然后,它让我想起了很久以前我在gdlib中遇到的另一个问题——关于PHP流函数、创建文件和HTTP。例如,像gdlib或pdf动态创建这样的图像库,它们在HTTP上都会失败。