po070157
po070157

Reputation: 51

List items from a .txt file using PHP

I have a text file "textlist.txt" with a list of items separated by a line break "br". How can I display that list inside my ordered list in html using PHP?

Txt file contents:

item1
item2
item3

Will like to use php to display like this

<li>item1</li>
<li>item2</li>
<li>item3</li>

I know how to read the file, but not to populate the contents of .txt in and html ordered list.

This is what I have

$myFile = "images/covers/lists/testlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;

All the covers in the list are being pulled with a glob function from a folder with the covers images. Now I'm trying to use the .txt file to label each cover (the title). Right Now is only listing the Last item from the .text file

    <?php $thumbs= glob( "images/covers/13colonies/*.jpg"); ?>
          <?php if(count($thumbs)) { natcasesort($thumbs);                      
            foreach($thumbs as $thumb) { ?>

     <?php $content = file('images/covers/lists/testlist.txt');
     foreach ($content as $line)  ?>

          <li>
          <img src="<?php echo $thumb ?>" width="80%" alt="images" />
                <h5 class="title"><?php echo $line ?></h5>
          </li>

          <?php }} else { echo "Sorry, no images to display!"; } ?>

Upvotes: 2

Views: 5549

Answers (4)

DowntimeDK
DowntimeDK

Reputation: 1

Something like this should work - this is just a simple list from a text file showing using HTML and PHP the content line by line but you can implement your $thumbs as well with a few modifications:

<label for="images">Choose an image:</label>
<select name="imagename" id="imageid">
<?php
$content = 
file('https://www.yoursite.ext/pathtotextfile/yourtextfile.txt');
$counter = 0; 
foreach ($content as $line)  {
$counter++; ?>
<option value=<" <?php echo "$counter"  ?> "> <?php echo "$line" ?> 
</option>
<?php  
} 
?> 

Upvotes: 0

user4704396
user4704396

Reputation:

$content = file('path/to/file.txt');

foreach ($content as $line) {
    echo ('<li>' . $line . '</li>);
}

The file() method reads the contents of the file to an array, with each line as its own element. You can then traverse through the array and do whatever you want with each line.

Link to documentation here.

Upvotes: 3

brother Filip
brother Filip

Reputation: 111

Using regular expressions:

echo preg_replace("/.+/", "<li>$0</li>", file_get_contents('file.txt'));

Upvotes: 0

Alex
Alex

Reputation: 713

$data = file_get_contents('file.txt');

$array = explode("\n" , $data);

foreach ($array as $line) {
     echo "<li>$line</li>";
}

Upvotes: 0

Related Questions