我有一个格式如下的txt文件:
string1 value
string2 value
string3 value
我必须解析从外部脚本更改的“值”,但 stringX 是静态的。我怎样才能得到每行的价值?
那应该对你有用。
$lines = file($filename);
$values = array();
foreach ($lines as $line) {
if (preg_match('/^string(\d+) ([A-Za-z]+)$/', $line, $matches)) {
$values[$matches[1]] = $matches[2];
}
}
print_r($values);
这可以帮助你。它一次读取一行,即使 Text.txt 包含 1000 行,如果您file_put_contents
每次都执行一次,例如file_put-contents("result.txt", $line[1])
,文件将在每次读取一行时更新(或您想要执行的任何操作),而不是之后读取所有 1000 行。在任何给定时间,内存中只有一行。
<?php
$fp = fopen("Text.txt", "r") or die("Couldn't open File");
while (!feof($fp)) { //Continue loading strings till the end of file
$line = fgets($fp, 1024); // Load one complete line
$line = explode(" ", $line);
// $line[0] equals to "stringX"
// $line[1] equals to "value"
// do something with $line[0] and/or $line[1]
// anything you do here will be executed immediately
// and will not wait for the Text.txt to end.
} //while loop ENDS
?>