略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ZipArchive::setArchiveComment

2024-11-14

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setArchiveCommentSet the comment of a ZIP archive

说明

public ZipArchive::setArchiveComment(string $comment): bool

Set the comment of a ZIP archive.

参数

comment

The contents of the comment.

返回值

成功时返回 true, 或者在失败时返回 false

范例

示例 #1 Create an archive and set a comment

<?php
$zip 
= new ZipArchive;
$res $zip->open('test.zip'ZipArchive::CREATE);
if (
$res === TRUE) {
    
$zip->addFromString('test.txt''file content goes here');
    
$zip->setArchiveComment('new archive comment');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>
add a noteadd a note

User Contributed Notes 2 notes

up
5
stanislav dot eckert at vizson dot de
7 years ago
Please note that ZIP archives do not support unicode encodings like UTF-8, so multi-byte characters cannot be shown in standard ZIP viewers like WinRAR or 7-zip. However, the text will stored as-is, so it is at least possible to display UTF-8 comments in your own desktop or web applications. If you want to test with PHP and output in a browser, don't forget to set page charset to UTF-8 too:

header("Content-Type: text/plain; charset=utf-8");
up
2
solrac at ragnarockradio dot com
5 years ago
Zip archives are encoded in ISO-8859-1 when stored but comments seem to be added in UTF-8 everytime. So...

<?php
   $zip
->setArchiveComment("Peña");    //outputs "Peña" as the comment.

  
$zip->setArchiveComment("Peña");    //outputs "NULL" as the comment / no comment is displayed.
?>

Using mb_internal_encoding() or mb_http_output() wont change this behavior.
At the end you can fix your corrupted comment using something like str_replace();

Consider this:

<?php
$zip
= new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if (
$res === TRUE) {
   
$zip->addFromString('test.txt', 'file content goes here');
   
$zip->setArchiveComment('Peña'); //outputs "Peña" as the comment.
   
$zip->close();
   
$file = file_get_contents('test.zip');
   
file_put_contents('test.zip', str_replace("Peña", utf8_decode("Peña"), $file)); //outputs "Peña" as the comment. FIXED!

   
echo 'ok';
} else {
    echo
'failed';
}
?>

官方地址:https://www.php.net/manual/en/ziparchive.setarchivecomment.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3