PHP:如何在我的页面上显示文本文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4754387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How do I display the contents of a textfile on my page?
提问by Phil
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.
我的 Web 服务器(本地)上有一个 .txt 文件,并希望通过 PHP 回显显示页面(存储在同一服务器上)中的内容。
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).
.txt 文件包含一个由另一个页面上的另一个脚本更新的数字,但对于这个页面,我只想从文件中提取数字/txt 文件内容并回显它(以保存页面必须执行的计算)再次得到号码)。
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;
?>
回答by
回答by StasM
回答by Phoenix
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.
如果您不想对文件中的内容做任何事情,只需显示它,实际上您可以只显示include()
它。 include
适用于任何文件类型,但当然它会运行它在里面找到的任何 php 代码。
回答by sspence65
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>';
回答by Robert Holland
I had to use nl2br to display the carriage returns correctly and it worked for me:
我必须使用 nl2br 才能正确显示回车符,它对我有用:
<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
回答by NeverRead
if you just want to show the file itself:
如果您只想显示文件本身:
header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);
回答by Sail
<?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
试试这个在 php 中打开一个文件
Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)
参考这个:(http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)