doutiao2540 2013-11-07 14:11
浏览 63

PHP - RecursiveDirectoryIterator + RecursiveIteratorIterator + RegexIterator的混合字符集文件名(拉丁语,日语,韩语)错误

I'm reading my music directory to populate a JSON for jPlayer, as follow:

<?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();
?>

The problem lies in files which filename isn't standard UTF-8 - as Latin, Japanese and Korean ones. Examples:

Japanese

enter image description here

Korean

enter image description here

Latin (pt-br)

enter image description here

Which converts into ?, or simply becomes null when parsing latin names ( Geração or for e.g.)

enter image description here


So, how make the filenames/paths be parsed correctly with different kinds of languages? The header charset isn't helping.

Info:

XAMPP with Apache2 + PHP 5.4.2 at Win7 x86


Update #1:

Tried @infinity's answer but no changes. Still ? on JP, null on Latin.

<?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();
?>

If I use HTML-ENTITIES instead of utf-8 on mb_substr(), latin characters works but asian still ?.

  • 写回答

4条回答 默认 最新

  • douqian1975 2013-11-12 17:08
    关注
    <?php
    header('Content-Type: application/json; charset=utf-8');
    mb_internal_encoding('utf-8');
    
    foreach ($Regex as $key => $value) {
        $whatever = mb_substr($key, 0, mb_strlen($str)-4, "utf-8");
        // ... rest of code
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度