PHP包,用于将文件扩展名转换为MIME类型,反之亦然。

3.0 2023-05-16 14:40 UTC

This package is auto-updated.

Last update: 2024-09-16 18:07:50 UTC


README

PHP包,用于将文件扩展名转换为MIME类型,反之亦然。

Build Status Coverage Status Code Climate Latest Stable Version Downloads per Month License

此包使用httpdmime.types来生成文件扩展名到MIME类型的映射,反之亦然。

mime.types文件由bin/generate.php解析,并转换为存储在mime.types.php中的优化PHP数组,该数组随后被辅助类\Mimey\MimeTypes包装。

用法

$mimes = new \Mimey\MimeTypes;

// Convert extension to MIME type:
$mimes->getMimeType('json'); // application/json

// Convert MIME type to extension:
$mimes->getExtension('application/json'); // json

获取全部

很少见,但有些扩展名有多个MIME类型

// Get all MIME types for an extension:
$mimes->getAllMimeTypes('wmz'); // array('application/x-ms-wmz', 'application/x-msmetafile')

然而,许多MIME类型有多个扩展名

// Get all extensions for a MIME type:
$mimes->getAllExtensions('image/jpeg'); // array('jpeg', 'jpg', 'jpe')

自定义转换

您可以通过更改给MimeTypes提供的映射来添加自定义转换。

有一个MimeMappingBuilder可以帮助完成这个任务

// Create a builder using the built-in conversions as the basis.
$builder = \Mimey\MimeMappingBuilder::create();

// Add a conversion. This conversion will take precedence over existing ones.
$builder->add('custom/mime-type', 'myextension');

$mimes = new \Mimey\MimeTypes($builder->getMapping());
$mimes->getMimeType('myextension'); // custom/mime-type
$mimes->getExtension('custom/mime-type'); // myextension

您可以将所需的所有转换添加到构建器中

$builder->add('custom/mime-type', 'myextension');
$builder->add('foo/bar', 'foobar');
$builder->add('foo/bar', 'fbar');
$builder->add('baz/qux', 'qux');
$builder->add('cat/qux', 'qux');
...

优化自定义转换加载

您可以通过在构建步骤中将所有转换保存到编译的PHP文件中来优化自定义转换的加载。

// Add a bunch of custom conversions.
$builder->add(...);
$builder->add(...);
$builder->add(...);
...
// Save the conversions to a cached file.
$builder->save($cache_file_path);

然后可以加载此文件以避免重复调用$builder->add(...)的开销

// Load the conversions from a cached file.
$builder = \Mimey\MimeMappingBuilder::load($cache_file_path);
$mimes = new \Mimey\MimeTypes($builder->getMapping());

安装

兼容PHP >= 5.4。

composer require ralouphie/mimey