toiteam
toiteam

Reputation: 61

Using a txt file to display links with php

I am trying to display a links using php and txt file.

My Text file (text.txt)

Spiderman, www.spiderman.com
See No Evil, www.seenoevil.com 

My php code so far (index.php);

<html>
<head>
<title>Reading from text files</title>

</head>
<body>

<?php
$f = fopen("text.txt", "r");

// Read line by line until end of file
while (!feof($f)) { 

// Make an array using comma as delimiter
   $arrM = explode(",",fgets($f)); 

// Write links (get the data in the array)
   echo "<li><a href='http://" . $arrM[1] . "'>" . $arrM[0]. "</a></li>"; 

}

fclose($f);
?>

</body>
</html>

Error I keep getting when I run index.php. This is what the browser displays; Error

Upvotes: 0

Views: 123

Answers (3)

Sarath Kn
Sarath Kn

Reputation: 2725

I think you opened the index.php directly in a browser. There is no error in this code. Try run it in the proper way .that is (localhost/yourDirectory/index.php)

Upvotes: 0

Deval Khandelwal
Deval Khandelwal

Reputation: 3548

If the browser gives you the output you have mentioned, this means that PHP has not been installed in your machine.Download and install WAMP server to execute php scripts.

But, if php has been installed, you are not using the server address, i.e. http://localhost/APP/. file:///C:/server/www/APP/ will not execute the php script.

Upvotes: 1

the_nuts
the_nuts

Reputation: 6054

You can use trim() to remove the whitespace and the new line characters, then it should work fine, I just tried:

(Also, make sure the txt file doesn't have the utf-8 BOM)

<html>
<head>
<title>Reading from text files</title>

</head>
<body>

<?php
$f = fopen("text.txt", "r");

// Read line by line until end of file
while (!feof($f)) { 

// Make an array using comma as delimiter
   $arrM = explode(",",fgets($f)); 

// Write links (get the data in the array)
   echo "<li><a href='http://" . trim($arrM[1]) . "'>" . trim($arrM[0]). "</a></li>"; 

}

fclose($f);
?>

</body>
</html>

Upvotes: 0

Related Questions