37

I have a .txt file on my web server (locally) and wish to display the contents within a page (stored on the same server) via PHP echo.

The .txt file contains a number that is updated by another script on another page, but for this page I just want to pull the number/txt file contents from the file and echo it (to save the page having to do the calculation involved in getting the number again).

How can I do this?

Here's what I've got so far:

    <?php
    $myFile = "http://renownestates.com/cache/feedSubscribers.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, 1);
    fclose($fh);
    echo $theData;
    ?>     

8 Answers 8

61

Here, try this (assuming it's a small file!):

<?php
echo file_get_contents( "filename.php" ); // get the contents, and echo it out.
?>

Documentation is here.

2
  • Does it matter if this code snippet is contained within the sidebar of a WordPress theme? ..ive replaced 'filename.php. with 'www.domain.com/myfile.txt' and its not working :(
    – Phil
    Jan 21, 2011 at 1:17
  • 1
    Aah, ive got it working now! took out the URL and just went ../fileLocation. Thank you!!!! :D
    – Phil
    Jan 21, 2011 at 1:22
13

For just reading file and outputting it the best one would be readfile.

1
  • This would return bytes of the file, not the content Apr 1, 2020 at 21:47
8

If you aren't looking to do anything to the stuff in the file, just display it, you can actually just include() it. include works for any file type, but of course it runs any php code it finds inside.

8

I had to use nl2br to display the carriage returns correctly and it worked for me:

<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
1
  • above can be used for .txt files too.
    – WhiteHorse
    Nov 15, 2018 at 17:11
5

I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:

$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);

echo '<code>';
echo '<pre>';

echo $a;

echo '</pre>';
echo '</code>';
3
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Try this to open a file in php

Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)

3

if you just want to show the file itself:

header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);
0

Use PHP's fopen

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.