本文介绍了我可以用PHP读取.TXT文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始用PHP和MySQL编写网站的过程时,我编写的第一个PHP脚本之一就是用于初始化数据库的脚本.删除/创建数据库.删除/创建每个表.然后从脚本中的文字加载表.

As I start the process of writing my site in PHP and MySQL, one of the first PHP scripts I've written is a script to initialize my database. Drop/create the database. Drop/create each of the tables. Then load the tables from literals in the script.

一切正常! Whoohoo:-)

That's all working fine! Whoohoo :-)

但是我更愿意从文件中读取数据,而不是在PHP脚本中对它们进行硬编码.

But I would prefer to read the data from files rather than hard-code them in the PHP script.

我有几本关于PHP的书,但它们都针对使用MySQL进行Web开发.我找不到有关读取和写入普通文件的任何信息.

I have a couple of books on PHP, but they're all oriented toward web development using MySQL. I can't find anything about reading and writing to ordinary files.

是的,我知道在stackoverflow上有大量关于读取TXT文件的问题,但是当我查看每个文件时,它们都是C或C#或VB或Perl的.我开始认为PHP不能读取文件:-(

Yes, I know there's a gazillion questions here on stackoverflow about reading TXT files, but when I look at each one, they're for C or C# or VB or Perl. I'm beginning to think that PHP just can't read files :-(

我只需要一个简短的PHP示例,说明如何在服务器上打开TXT文件,依次读取文件,在屏幕上显示数据并关闭文件,如以下伪代码所示:

All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:

program readfile;
handle = open('myfile.txt');
data = read (handle);
while (not eof (handle)) begin
    display data;
    data = read (handle);
    end;
close (handle);
end;

当我到达人们上传头像的网站部分并将它们另存为JPG或GIF文件时,我还需要在服务器上写文件.但这是待会儿.

I will also need to write files on the server when I get to the part of my site where people upload avatars, and save them as JPG or GIF files. But that's for later.

谢谢!

推荐答案

来自 :

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

编辑根据评论,您可以使用 fgets()

EDITper the comment, you can read a file line by line with fgets()

<?php
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

这篇关于我可以用PHP读取.TXT文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:01