我正在阅读我的音乐目录来为 jPlayer 填充 JSON,如下所示:
<?php
//tried utf-8, shift_jis, etc. No difference
header('Content-Type: application/json; charset=SHIFT_JIS');
//cant be blank so i put . to make current file dir as base
$Directory = new RecursiveDirectoryIterator('.');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.mp3$/i', RecursiveRegexIterator::GET_MATCH);
//instead of glob(*/*.mp3) because isnt recursive
$filesJson = [];
foreach ($Regex as $key => $value) {
$whatever = str_ireplace(['.mp3','.\\'], '', $key);
$filesJson['mp3'][] = [
'title' => htmlspecialchars($whatever),
'mp3' => $key
];
}
echo json_encode($filesJson);
exit();
?>
问题在于文件名不是标准 UTF-8 的文件——如拉丁文、日文和韩文。例子:
日本人
韩国人
拉丁语 (pt-br)
在解析拉丁名称(或例如)时转换为?
,或简单地变为null
Geração
4º
那么,如何使用不同类型的语言正确解析文件名/路径?标题字符集没有帮助。
信息:
XAMPP 与 Apache2 + PHP 5.4.2 在 Win7 x86
更新#1:
尝试了@infinity 的答案,但没有任何变化。仍然?
在 JP 上,null
在拉丁语上。
<?php
header('Content-Type: application/json; charset=UTF-8');
mb_internal_encoding('UTF-8');
$Directory = new RecursiveDirectoryIterator('.');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.mp3$/i', RecursiveRegexIterator::GET_MATCH);
$filesJson = [];
foreach ($Regex as $key => $value) {
$whatever = mb_substr($key, 2, mb_strlen($key)-6, "utf-8"); // 2 to remove .\ and -6 to remove .mp3 (-4 + -2)
$filesJson['mp3'][] = [
'title' => $whatever, //tried with and without htmlspecialchars
'mp3' => $key
];
}
echo json_encode($filesJson);
exit();
?>
如果我使用HTML-ENTITIES
而不是utf-8
on mb_substr()
,拉丁字符可以工作,但亚洲字符仍然有效?
。