Jenson M John
Jenson M John

Reputation: 5689

PHP List all files in a directory with Unicode Filenames

Well, I've these JSON files in my directory & The filename contain Unicode Characters.

"Spanish - Estoy leyendo este archivo.json"
"Malayalam - ഞാൻ ഈ ഫയൽ വായിക്കുന്നു.json"
"Greek - Διαβάζω αυτό το αρχείο.json"
"Japanese - このファイルを読んでいます.json"
"English - I am reading this file.json"

I'm trying to list all files using scandir function with the below snippet.

<?php
 $dir    = './';
 $files = scandir($dir);

 echo "<pre>";
 print_r($files);
 echo "</pre>";
?>

But I'm not getting actual filenames but like below.

Array
(
    [0] => .
    [1] => ..
    [2] => English - I am reading this file.json
    [3] => Greek - ??a�??? a?t? t? a??e??.json
    [4] => Japanese - ?????????????.json
    [5] => Malayalam - ??? ? ??? ????????????.json
    [6] => Spanish - Estoy leyendo este archivo.json
    [7] => index.php
)

What is the Correct way to achieve the Same??

Upvotes: 1

Views: 370

Answers (1)

smartdroid
smartdroid

Reputation: 311

Seems the webserver is not using utf-8 character set in the header (double check response header in your browser's console->network tab).

So even if the php variable contains the correct filename, the browser is not expecting utf-8 characters and showing them wrong. Try explicitly setting the character set in php:

<?php
 header('Content-type: text/html; charset=utf-8');
 $dir    = './';
 $files = scandir($dir);

 echo "<pre>";
 print_r($files);
 echo "</pre>";
?>

Upvotes: 1

Related Questions