I've created a simple PHP script which reads .txt files (1.txt, 2.txt etc which each contain dummy text: "Test~Test test test test test test") and produces a html output of each file's content with a little html formatting.

<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>

This currently works just fine. The problem is that if I was to create the file 4.txt, I would have to hard code the $number variable to 4.

I have tried to automatically initialise $number to the highest number.txt. I need help creating a loop which would use the file_exists() function to test if a file x.txt exists, if it does then increment x and test again. If it doesn't exist, the loop should instead break out and hence I could just say $number=x.

I hope this explanation is clear enough, thank you for your time.

有帮助吗?

解决方案

Use glob(), your method is pretty bad:

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

What you want to do is $arr = glob("*.txt"); and then loop through that array.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top