PHP:无法使用 php 从文本文件中逐行检索文本


PHP:Can't retrieve line by line text from a text file with php

我的服务器中有一个动态变化的文本文件,我想在我的php页面中打印文本文件的特定行,我也想修剪当前行。例如,假设数据.txt

score=36
name=Football Cup
Player=albert

我想在我的页面中打印这样的内容
36
足球杯
阿尔伯特

那么我如何从动态更改的文本文件中打印特定的单词或句子。

在这种情况下,您所需要的只是:

foreach(file("data.txt") as $line) {
    list($k,$v) = explode("=",$line,2);
    echo $v."<br />";
}

如果您运行的是 PHP 5.4,则可以使用较短的:

foreach(file("data.txt") as $line) echo explode("=",$line,2)[1]."<br />";

如果它总是name=WORD那么你可以这样做:

$file = file('data.txt')
// iterate through every line:
foreach($file as $line) {
  // split at the '=' char
  $parts = explode('=', $line, 2); // limit to max 2 splits
  // and the get the second part of it
  echo $parts[1];
}

如果数据始终采用该格式或类似格式,则可以使用 PHP 的内置配置文件解析器加载数据,然后通过数组索引引用其值。

$data = parse_ini_file( "data.txt" );
echo $data["name"]."'n";

无需字符串操作或 for 循环。