0

我有一个格式如下的txt文件:

string1 value
string2 value
string3 value

我必须解析从外部脚本更改的“值”,但 stringX 是静态的。我怎样才能得到每行的价值?

4

2 回答 2

2

那应该对你有用。

$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);
于 2012-07-09T08:28:03.287 回答
1

这可以帮助你。它一次读取一行,即使 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

?>
于 2012-07-09T08:39:56.063 回答