这篇小博文向您展示了如何使用 PHP 读取 ZIP/JAR 文件条目,并解析 JAR 清单 (MANIFEST.MF) 文件。就是这样。没有什么花哨。
1.读取JAR/ZIP文件入口
首先,我们需要从 JAR 文件中读取 MANIFEST.MF 文件。由于 JAR 文件只不过是一个 ZIP 文件,因此可以使用PHP 的zip_*函数。
<?php
function readZipFileEntry($zipFileName, $searchEntryName) {
$zip = zip_open($zipFileName);
if ($zip) {
while ($zipEntry = zip_read($zip)) {
$entryName = zip_entry_name($zipEntry);
if ($entryName == $searchEntryName) {
if (zip_entry_open($zip, $zipEntry, "r")) {
$searchFileContents = zip_entry_read($zipEntry, zip_entry_filesize($zipEntry));
zip_entry_close($zipEntry);
zip_close($zip);
return $searchFileContents;
}
}
}
zip_close($zip);
}
return false;
}
2.解析JAR文件清单(MANIFEST.MF)
完成此操作后,需要解析 MANIFEST.MF。清单文件具有非常简单的键值格式,以冒号 (:) 作为分隔符。这段代码为我们做了解析:
function parseJarManifest($manifestFileContents) {
$manifest = array();
$lines = explode("\n", $manifestFileContents);
foreach ($lines as $line) {
if (preg_match("/^([^:]+):\s*(.+)$/", $line, $m)) {
$manifest[$m[1]] = trim($m[2]);
}
}
return $manifest;
}
- 使用功能
结合这两种功能,我们可以读到一个ZIP文件条目的内容readZipFileEntry()和解析与JAR文件清单parseJarManifest() :
$manifestFileContents = readZipFileEntry("syncany-plugin-samba-0.4.0-alpha.jar", "META-INF/MANIFEST.MF");
$manifest = parseJarManifest($manifestFileContents);
print_r($manifest);
/*
Array
(
[Manifest-Version] => 1.0
[Plugin-Id] => samba
[Plugin-Name] => Samba
[Plugin-Version] => 0.4.0-alpha
[Plugin-Operating-System] => all
[Plugin-Architecture] => all
[Plugin-Date] => Sun Dec 28 16:37:19 UTC 2014
[Plugin-App-Min-Version] => 0.4.0-alpha
[Plugin-Release] => true
[Plugin-Conflicts-With] =>
)
*/