【问题标题】:PHP Check filenamesPHP 检查文件名
【发布时间】:2014-03-23 19:14:24
【问题描述】:

我创建了一个简单的 PHP 脚本,它读取 .txt 文件(1.txt、2.txt 等,每个文件都包含虚拟文本:“Test~Test test test test test”)并生成每个文件的 html 输出带有一点 html 格式的内容。

<html>
<head>
    <style type="text/css">
        body {background-color: #80B2FF; font-family: arial,sans-serif;}
        .content {background-color: #ffffff; margin: 35px auto; max-width: 75%; padding: 35px;}
    </style>
</head>
<body>
<?php
for ($number = 3; $number>=1; $number--){
    $article = $number.".txt";
    $data = file_get_contents($article); //read the file
    $convert = explode("~", $data); //create array separate by new line
    echo '<div class="content">'.$convert[0].'<br/><br/>'; //write value by index 0
    echo $convert[1].'<br/><br/>'.'</div>'; //write value by index 0
}
?>
</body>
</html>

这目前工作得很好。问题是,如果我要创建文件 4.txt,我必须将 $number 变量硬编码为 4。

我尝试将 $number 自动初始化为最高的 number.txt。我需要帮助创建一个循环,该循环将使用 file_exists() 函数来测试文件 x.txt 是否存在,如果存在则增加 x 并再次测试。如果它不存在,那么循环应该会中断,因此我只能说 $number=x。

我希望这个解释足够清楚,谢谢你的时间。

【问题讨论】:

  • 首先,使用数据库。这要容易得多。其次,如果你热衷于使用这种方法,你可以看看glob
  • 使用glob() 从目录中获取文件列表,并使用它来确定要读取的文件。
  • 您在编写使用file_exists 的循环时遇到什么问题?这似乎微不足道?

标签: php filenames file-exists


【解决方案1】:

使用glob(),你的方法很糟糕:

http://php.net/globhttp://www.w3schools.com/Php/func_filesystem_glob.asp

您要做的是$arr = glob("*.txt");,然后循环遍历该数组。

【讨论】:

  • 请注意 glob 的警告......默认情况下,它会按名称对文件进行排序,但不是以一种理智的方式。例如,1.txt、10.txt、2.txt、3.txt。要解决此问题,请使用 natsort($arr);之后,如果您的订单很重要。
  • @rjdown 这就是 all UNIX 工具对文件进行排序的方式,与 PHP 的 glob() 函数无关。像这样对文件进行排序也很有意义,恕我直言,因为这是排序的工作原理......
  • @Carpetsmoker 我知道,我只是指出此答案返回的结果与 OP 代码中的顺序不匹配,因此需要一些摆弄。事实上,再看一遍他需要做 array_reverse(natsort($arr)) !!
  • 谢谢,现在一切都按照我的预期工作了,更新后的 PHP: $val){ $array[$key] = substr($val, 0, -4); } for ($number = max($array); $number>=1; $number--){ $article = $number.".txt"; $data = file_get_contents($article); //读取文件 $convert = explode("~", $data); //创建由新行分隔的数组 echo '
    '.$convert[0].'

    '; //按索引0写入值 echo $convert[1].'

    '.'
    '; //按索引 0 写入值 } ?>
猜你喜欢
  • 2012-04-18
  • 2011-11-25
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2013-12-16
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多