Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How do I display the contents of a textfile on my page?

Tags:

php

echo

People also ask

How do you display text in PHP?

PHP allows us to display the text in various formats using various inbuilt methods. Using echo command: The echo command can be used to display text, including numerical, strings and arrays.

How do I open and display a file in PHP?

$myfile = fopen("webdictionary. txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary. txt"));


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.


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


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.
?>

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.


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>';

<?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)