2012-07-09 69 views
0

我有此格式的TXT文件:从PHP文件中读取与空间

string1 value 
string2 value 
string3 value 

我要解析的“价值”从外部脚本的变化,但字符串X是静态的。 我怎样才能得到每行的价值?

+2

你有没有试过自己的东西? – Stony 2012-07-09 08:24:14

+0

在询问前对谷歌做了一些调查 – 2012-07-09 08:24:59

+0

我对这个空间有问题,我不知道该如何处理它。 – user840718 2012-07-09 08:25:32

回答

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); 
+1

它的工作,但不是一个非常好的解决方案,当文件非常大。然后你,但所有的数组和内存。也许最好是阅读文件的每一行并使用它。 – Stony 2012-07-09 08:29:41

+1

没错。不过他可能会自己做一些研究 - 他迄今为止没有提及的。 – fdomig 2012-07-09 08:35:55

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 

?>