简体   繁体   中英

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; 错误

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, ie http://localhost/APP/ . file:///C:/server/www/APP/ will not execute the php script.

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>

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM