符号问题(scandir,array_diff,foreach)

时间:2017-08-09 07:57:23

标签: php encoding symbols entities scandir

我正在尝试编写一个打开目录的脚本,扫描所有文件(图像)并在屏幕上显示它,但问题是,它的名称中包含符号,scandir无法处理它。

对于名称中没有符号的目录没问题,脚本工作正常,但名称中包含符号的目录/文件是个大问题。

例如,我有2个目录,该目录中的所有文件名称中包含相同的符号。一个包含“®”,另一个包含“™”,每个文件(图像)的名称都包含这些符号,例如:“Right®screen452217.jpg”。因此,重命名目录和文件不是一种选择,这将花费太多时间。

也许有更好的方法,但我直接从屏幕上的url使用$ _GET。它现在在本地服务器上,我在VertrigoServ WAMP服务器上工作,然后脚本如下:

flatMap

scandir报告了这些错误:

http://127.0.0.1/screenshots/index.php?page=Rights®
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks™

$url = "screens/".$_GET["page"]."";
$scan = scandir($url, SCANDIR_SORT_NONE);
$scaned = array_diff($scan, array('.', '..', 'Thumbs.db'));

foreach($scaned as $shots) {

    if ($shots <> "thumbnails") {

echo "<li>".PHP_EOL.
     " <img width=\"253\" height=\"158\" src=\"".$url."\\".$shots."\"".
     "  alt=\"".$shots."\" title=\"".$shots."\".
     " </li>".PHP_EOL.PHP_EOL;

    }

}

array_diff报告此错误:

The system cannot find the file specified. (code: 2)
failed to open dir: No such file or directory
No such file or directory

最后是foreach报告:

Argument #1 is not an array

我还尝试使用mb_convert_encoding()iconv()更改编码,但没有运气。

我最好的结果是在更改网址后,而不是使用“®”或“™”我使用了windows-1252 ASCII Encoding Reference

Invalid argument supplied for foreach()

然后一切都没有错误传递,但是“img src”看起来像是:

而不是显示图像。
http://127.0.0.1/screenshots/index.php?page=Rights%AE
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks%99

这仍然有问题,因为不显示图像。我喜欢坚持使用scandir,因为我已经完成了页面,但我不能用符号来解决这个问题。你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

它实际上比我想象的要简单。问题是,该目录的名称中已经包含符号,因此我必须将其更改为Windows-1252:

$page = $_GET["page"];

if (strpos($page, '®')) {$page = str_replace('®', '%AE', $page);}
if (strpos($page, '™')) {$page = str_replace('™', '%99', $page);}

然后网址改为:

http://127.0.0.1/screenshots/index.php?page=Rights®
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks™

要:

http://127.0.0.1/screenshots/index.php?page=Rights%AE
http://127.0.0.1/screenshots/index.php?page=Trade%20Marks%99

然后很简单,只需在scandir之后添加编码,在foreach中添加一个编码:

$url = "screens/".$_GET["page"]."";
$scan = scandir($url, SCANDIR_SORT_NONE);
$scaned = array_diff($scan, array('.', '..', 'Thumbs.db'));

$url = iconv("windows-1252", "UTF-8", $screen_uplay);

foreach($scaned as $shots) {

    if ($shots <> "thumbnails") {

    $shots = iconv("windows-1252", "UTF-8", $shots);

echo "<li>".PHP_EOL.
     " <img width=\"253\" height=\"158\" src=\"".$url."\\".$shots."\"".
     "  alt=\"".$shots."\" title=\"".$shots."\".
     " </li>".PHP_EOL.PHP_EOL;

    }

}

这很简单。也许有更好的方法,但这对我有用,我对此很满意。