我在服务器上有一个包含以下信息的文本文件:
Data1
Data2
Data3
.
.
.
DataN
如何使用PHP逐行读取文本文件中的所有信息?
<?php
$fh = fopen('filename.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
// echo($line);
}
fclose($fh);
?>
这将为您提供逐行读取..请查看php.net/fgets中有关Mac计算机换行问题的注意事项。
http://php.net/manual/zh/function.file-get-contents.php
http://php.net/manual/zh/function.explode.php
$array = explode("\n", file_get_contents($filename));
这并不会逐行读取文本,但是它将返回一个数组,可以按行使用。有许多替代方法。
$filename = "file.txt";
$lines = array();
$fp = fopen($filename, "r");
if(filesize($filename) > 0){
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
fclose($fp);
}
print_r($lines);
这段代码将文件的全部内容复制到变量$content
中,并将其使用每个换行符在数组变量$lines
中拆分。
你也可以使用文件来生成数组:
$array = file('/path/to/text.txt');
W3Schools是您的好朋友:http://www.w3schools.com/php/func_filesystem_fgets.asp
还有这里:http://php.net/manual/en/function.fopen.php 有更多关于fopen的信息,包括模式。
W3Schools的说法:
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
fopen函数打开文件(在本例中为test.txt),模式为“r”,表示只读,并将指针放在文件开头
while循环检查是否到达文件末尾(feof),如果没有,则调用fgets获取指针所在的当前行。
重复执行此操作,直到到达文件末尾,然后关闭文件。
试着像这样做:
$filename = 'file.txt';
$data = file($filename);
foreach ($data as $line_num=>$line)
{
echo 'Line # <b>'.$line_num.'</b>:'.$line.'<br/>';
}
$file="./doc.txt";
$doc=file_get_contents($file);
$line=explode("\n",$doc);
foreach($line as $newline){
echo '<h3 style="color:#453288">'.$newline.'</h3><br>';
}
除非明确指定字符串的处理位置和方式,否则只需使用 file_get_contents()。不需要长时间的迭代和解决方法。
例如,在/client/中从 latestversion.txt 读取版本,并使用三元运算符(条件? do:else)进行回退。
$version = file_exists("client/latestversion.txt") ? file_get_contents("client/latestversion.txt") : "0.0.0.0";
echo "The version is: " . $version;
或者你可以这样调用它
printf("The version is: %s", $version);
上面从Payload发布的代码非常好用。我想添加一些内容,因为其他人可能会遇到同样的问题。我使用了您的代码,并尝试将值与从.txt文件中提取的$line进行比较。即使我知道我的关键字匹配一行,我仍然不断收到错误。这是一个代码示例...
textfile.txt content example:
text1
text2
keyword
text3
$keyword = 'keyword';
while($line = fgets($txt_file)) {
if (substr_compare($line, $keyword, 0) === 0) {
$value = $line;
}
}
echo $value; // returns nothing because the if statement was false
while($line = trim(fgets($txt_file))) {
if (substr_compare($line, $keyword, 0) === 0) {
$value = $line;
}
}
echo $value; // result: keyword
是的,我尝试在substr_compare()函数中将trim()应用于$line时得到了一些奇怪的结果,即使if语句的结果为TRUE,$value也会有一个以空格开头和结尾的"关键字"结果。真是奇怪的事情...
$your_variable = file_get_contents("file_to_read.txt");
你的变量 = file_get_contents("file_to_read.txt");