PHP Conference Japan 2024

ZipArchive::setArchiveComment

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

ZipArchive::setArchiveComment設定 ZIP 封存的註解

說明

public ZipArchive::setArchiveComment(字串 $comment): 布林值

設定 ZIP 封存的註解。

參數

comment

註解的內容。

回傳值

成功時回傳 true,失敗時回傳 false

範例

範例 #1 建立封存並設定註解

<?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';
}
?>
新增註釋

使用者貢獻的註釋 3 則註釋

stanislav dot eckert at vizson dot de
9 年前
請注意,ZIP 壓縮檔不支援 UTF-8 等 Unicode 編碼,因此多位元組字元無法在 WinRAR 或 7-zip 等標準 ZIP 檢視器中顯示。然而,文字會照原樣儲存,因此至少可以在您自己的桌面或網路應用程式中顯示 UTF-8 註釋。如果您想使用 PHP 進行測試並在瀏覽器中輸出,也別忘了將頁面字元集設定為 UTF-8。

header("Content-Type: text/plain; charset=utf-8");
solrac at ragnarockradio dot com
8 年前
ZIP 壓縮檔在儲存時以 ISO-8859-1 編碼,但註釋似乎每次都以 UTF-8 新增。所以...

<?php
$zip
->setArchiveComment("Peña"); // 輸出 "Peña" 作為註釋。

$zip->setArchiveComment("Peña"); // 輸出 "NULL" 作為註釋 / 沒有顯示註釋。
?>

使用 mb_internal_encoding() 或 mb_http_output() 不會改變這種行為。
最後,您可以使用 str_replace() 之類的函式修復損壞的註釋。

考慮這一點

<?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'); // 輸出 "Peña" 作為註釋
$zip->close();
$file = file_get_contents('test.zip');
file_put_contents('test.zip', str_replace("Peña", utf8_decode("Peña"), $file)); // 輸出 "Peña" 作為註釋。已修正!

echo 'ok';
} else {
echo
'failed';
}
?>
poetbi at boasoft dot cn
1 年前
ZipArchive(使用 libzip)以 UTF-8/ASCII 編碼註釋,但 Windows 上的某些軟體以 ANSI(例如 GBK...)顯示註釋,因此我們應該

<?php
$_charset
= 'GBK';
$file = 'D:/boaphp.zip';
$comment = '中文ABC123';

$zip = new ZipArchive;
$res = $zip->open($file, ZipArchive::CREATE);
if (
$res) {
//在此處新增檔案

if($_charset){ //適用於 WinRAR、7z 等壓縮軟體
$zip->close();

$str = mb_convert_encoding($comment, $_charset, 'UTF-8');
$fh = fopen($file, 'r+b');
fseek($fh, -2, SEEK_END);
$str = pack('v', strlen($str)) . $str;
fwrite($fh, $str);
fclose($fh);
}else{
//適用於 PHP: $zip->getArchiveComment()
$zip->setArchiveComment($comment);
$zip->close();
}
}
?>
To Top