2024 年 PHP 日本研討會

轉換篩選器

如同 string.* 篩選器,convert.* 篩選器執行的動作與其名稱相似。有關特定篩選器的更多資訊,請參閱對應函式的說明頁面。

convert.base64-encode 和 convert.base64-decode

使用這些篩選器等同於分別透過 base64_encode()base64_decode() 函式處理所有串流資料。 convert.base64-encode 支援以關聯陣列提供的參數。如果提供 line-length,base64 輸出將會分割成每個區塊 line-length 個字元。如果提供 line-break-chars,每個區塊將會以提供的字元分隔。這些參數的效果與使用 base64_encode() 搭配 chunk_split() 相同。

範例 #1 convert.base64-encode & convert.base64-decode

<?php
$fp
= fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* 輸出:VGhpcyBpcyBhIHRlc3QuCg== */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* 輸出:VGhpcyBp
: cyBhIHRl
: c3QuCg== */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* 輸出:This is a test. */
?>

convert.quoted-printable-encode 和 convert.quoted-printable-decode

使用這個過濾器的解碼版本等同於透過 quoted_printable_decode() 函式處理所有串流資料。沒有函式等同於 convert.quoted-printable-encodeconvert.quoted-printable-encode 支援以關聯陣列形式給出的參數。除了 convert.base64-encode 支援的參數之外,convert.quoted-printable-encode 也支援布林值參數 binaryforce-encode-firstconvert.base64-decode 只支援 line-break-chars 參數作為從編碼的有效負載中去除的類型提示。

範例 #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp
= fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* 輸出:=This is a test.=0A */
?>

convert.iconv.*

如果啟用了 iconv 支援,則可以使用 convert.iconv.* 篩選器,其作用等同於使用 iconv() 處理所有串流資料。這些篩選器不支援參數,而是期望輸入和輸出編碼作為篩選器名稱的一部分提供,例如 convert.iconv.<輸入編碼>.<輸出編碼>convert.iconv.<輸入編碼>/<輸出編碼>(兩種表示法在語義上相同)。

範例 #3 convert.iconv.*

<?php
$fp
= fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* 輸出:This is a test. */
?>
新增註釋

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

-2
marcus at synchromedia dot co dot uk
2 年前
convert.quoted-printable-encode 的所有可用參數並不十分明顯。如果您希望串流篩選器以與 quoted_printable_encode 函式相同的方式運作,則需要這些額外參數,例如

stream_filter_append(
STDOUT,
'convert.quoted-printable-encode',
STREAM_FILTER_WRITE,
[
'line-break-chars' => PHP_EOL,
'line-length' => 75,
]
);
echo stream_copy_to_stream(STDIN, STDOUT);

如果未設定這些額外參數,您可能根本沒有換行,或者使用錯誤的換行符號序列換行。
To Top