<?php
$list = scandir2('sample');
echo '<pre>';
var_dump($list);
echo '</pre>';
function scandir2($dp){
$files = scandir($dp);
$enclist = array(
'UTF-8','SJIS','ASCII' ,
);
$code_str = join(',', $enclist);
echo "<table class='tbl2'><tbody>";
foreach($files as $file){
if($file=='.' || $file=='..'){
continue;
}
echo '<tr>';
echo '<td>' . urlencode($file) . '</td>';
$enc = mb_detect_encoding($file,$code_str);
$file= mb_convert_encoding($file,"UTF-8",$enc);
$enc2 = mb_detect_encoding($file);
echo '<td>' . $enc . '</td>';
echo '<td>' . $enc2 . '</td>';
echo '<td>' . $file . '</td>';
$files2[] = $file;
echo '</tr>';
}
echo '</tbody></table>';
return $files2;
}
?>
出力
| cat.txt | UTF-8 | ASCII | cat.txt |
| %D7%97%D7%AA%D7%95%D7%9C.txt | UTF-8 | UTF-8 | חתול.txt |
| %E0%A6%95.txt | UTF-8 | UTF-8 | ক.txt |
| %E4%B8%80%E9%9A%BB%E8%B2%93.txt | UTF-8 | UTF-8 | 一隻貓.txt |
| %E7%8C%AB.txt | UTF-8 | UTF-8 | 猫.txt |
| %EA%B3%A0%EC%96%91%EC%9D%B4.txt | UTF-8 | UTF-8 | 고양이.txt |
array(6) {
[0]=>
string(7) "cat.txt"
[1]=>
string(12) "חתול.txt"
[2]=>
string(7) "ক.txt"
[3]=>
string(13) "一隻貓.txt"
[4]=>
string(7) "猫.txt"
[5]=>
string(13) "고양이.txt"
}
<?php
$list = scandirEx('sample');
echo '<pre>';
var_dump($list);
echo '</pre>';
/**
* ディレクトリ内のファイル一覧を取得(外国語ファイル名に対応)
*
* @note
* さくらサーバー(スタンダードプラン)である場合、ファイル名が外国語でも取得可能。半角英数字はASCII、他言語はUTF-8として取得される。
* 一般的なローカル環境(Windows)である場合、半角英数字はASCII、日本語はUTF-8、多言語は文字化けする。
*
* 外国語のファイル名を取得したい場合、サーバーのOSレベルでの設定が必要になってくる。
*
* @param unknown $dp
* @param string $str_code
* @return string
*/
function scandirEx($dp,$str_code='UTF-8,SJIS,ASCII'){
$files = scandir($dp);
foreach($files as $file){
if($file=='.' || $file=='..'){
continue;
}
$enc = mb_detect_encoding($file,$str_code);
$file= mb_convert_encoding($file,"UTF-8",$enc);
$files2[] = $file;
}
return $files2;
}
?>
出力
array(6) {
[0]=>
string(7) "cat.txt"
[1]=>
string(12) "חתול.txt"
[2]=>
string(7) "ক.txt"
[3]=>
string(13) "一隻貓.txt"
[4]=>
string(7) "猫.txt"
[5]=>
string(13) "고양이.txt"
}