enorris/mbstring-stream

一个mbstring流转换过滤器。

v3.0.1 2023-11-05 20:16 UTC

This package is auto-updated.

Last update: 2024-09-05 22:22:14 UTC


README

这是一个php_user_filter实现,可以快速转换流字符集,而无需将整个字符串加载到内存中。

注意:此库没有为状态性字符集持久化状态的能力,因此可能会丢失数据。请参阅#1中的开放问题,以及此文档获取有关状态性字符集的更多信息。

示例

// Not required if the file was autoloaded (e.g. using composer)
MultibyteStringStream::registerStreamFilter();

$native_file = fopen('iso-8859-1-file.txt', 'r');

stream_filter_append($native_file, 'convert.mbstring.UTF-8/ISO-8859-1');

$unicode_file = fopen('utf8-file.txt', 'w');

stream_copy_to_stream($native_file, $unicode_file);

mbstring-stream 也可以作为写过滤器使用

$native_file  = fopen('sjis-file.txt', 'r');
$unicode_file = fopen('utf8-file.txt', 'w');

stream_filter_append($unicode_file, 'convert.mbstring.UTF-8/SJIS');

stream_copy_to_stream($native_file, $unicode_file);

用法

/**
 * resource   $stream        The stream to filter.
 * string     $to_encoding   The encoding to convert to.
 * string     $from_encoding The encoding to convert from. Optional, defaults to mb_internal_encoding()
 * int        $read_write    See https://php.ac.cn/manual/en/function.stream-filter-append.php
 * string|int $sub_char      The substitute character to use. Optional, defaults to mb_substitute_character()
 */
stream_filter_append($stream, "convert.mbstring.$to_encoding/$from_encoding", $read_write, $sub_char);

注意:在使用“r+”或“w+”(或类似)模式的流时要小心;默认情况下,PHP将过滤器分配给读取和写入链。这意味着它将尝试两次转换数据 - 一次在写入流时,一次在从流中读取时。