Search code examples
phpfunctionloopsforeachgenfromtxt

PHP - Getting text from a text file and using them in a "loop"!


Im new to php, and i really need some help with this script. I have a text file with names(serverlist.txt). The first line of code gets these names. I want it to get one name, put it in to the last bit of code(), Then repeat the process untill there are no lines of text in the serverlist.txt.

Please help me.

    <?php 
$file = 'serverlist.txt';
$content = "";
if($handle = fopen($file, 'r')) {
    while(!feof($handle)) {
        $content .= fgets($handle);
            foreach($content as $cont) {
            }
    }
    fclose($handle);
}



?>

<html>
<head>
</head>
<body>
<img src="http://minecraft.net/skin/<?php 


echo $cont; ?>.png" alt="">

</body>
</html>

Solution

  • You could store the output of the server names in a variable and then output them in your HTML body.

    <?php 
      $file = 'serverlist.txt';
      $servers = '';
      if ($handle = fopen($file, 'r')) {
        while (!feof($handle)) {
          $content = trim(fgets($handle));
          $names = explode(' ', $content);
          foreach ($names as $name) {
            $servers .= '<img src="http://minecraft.net/skin/' . $name. '.png" alt="">';
          }
        }
       fclose($handle);
      }
    ?>
    
    <html>
    <head>
    </head>
    <body>
      <?php echo $servers; ?>
    </body>
    </html>