Search code examples
phpfgets

Styling each result of an fgets($file) list differently, is it possible?


G'day, first post so here we go. Very open to suggestions as I'm not sure if it's possible to do what I want with the type of coding I am using. Kinda new/rusty to coding, been a LOOOONG time.

Purpose of current coding:

I have a .txt file with a list of file names (map names to be exact for my situation, each on it's own line) that is constantly being changed and modified as we add/remove maps. I am using a script on a .php page to parse the contents of that file and display the results on a webpage. The script outputs each map name to a variable that is wrapped in an href tag, which results in a link to download that particular map. This continues until all maps have been created in a list, each as a link to download that map.

Problem I am having:

I do not wish some maps/entries to be created as links, and only as text. Is there a way to filter the results of an fgets() and style them different based on value? So like map1-map4 all get turned into download links but map5 does not, then map6 and on continue to be download links.

Current script/code being used:

<?php
$file = fopen("maplists/dodgeball.ini", "r");

while (!feof($file)) {
    $dbmapname[] = fgets($file);
}
fclose($file);


foreach ($dbmapname as $dbmap){
echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
}
?>

Coding revised thanks to help below. Here is my current coding to produce what I was looking for:

foreach ($dbmapname as $dbmap){
if(!in_array($dbmap, $stockmaps)){
echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
}
else echo $dbmap."<br />";
}

I am still having a slight issue though regarding the last entry of the array being forced to be a link regardless if it is in the $stockmaps array or not.


Solution

  • There are a ton of ways to implement this. Below I've presented a nice general way where you create an array of maps for which you don't want a link and then loop through and print either link or the plain text depending on whether each map is in the list.

    <?php
    $file = fopen("maplists/dodgeball.ini", "r");
    
    while (!feof($file)) {
        $dbmapname[] = trim(fgets($file));
    }
    fclose($file);
    
    $nolink = array( $dbmapname[4] ); //fifth map
    
    foreach ($dbmapname as $dbmap){
      if(!in_array($dbmap, $nolink)){
        echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
      }
      else echo $dbmap."<br />";
    }
    }
    ?>
    

    You can add item to the filter based on whatever criteria you want

    //Add item 2 to the list
    $nolink[] = $dbmapname[1];
    
    //Add all items after item 20 to the list
    $nolink = array_merge($nolink, array_slice($dbmapname, 20));
    
    //Don't link a specific set of maps
    $nolink = array('bad_map', 'another_map_not_to_show');