2012-07-09 71 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 

?>