Reputation: 1611
I have a txt file formatted like this:
string1 value
string2 value
string3 value
I have to parse the "value" that change from an external script, but the stringX are static. How can I get the value by each line?
Upvotes: 0
Views: 1485
Reputation: 1976
This could help you. It reads one line at a time, and even if Text.txt contains 1000 lines, if you do a file_put_contents
each time, like file_put-contents("result.txt", $line[1])
, file will be updated every time it reads a line (or any action you want will be executed), not after reading all the 1000 lines. And at any given time, only one line is in memory.
<?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
?>
Upvotes: 1
Reputation: 4457
That should work for you.
$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);
Upvotes: 2