2013-02-14 77 views
0

有沒有一種簡單的方法可以解析下面將要發佈的以下數據。數據來自網絡。用PHP解析格式化的文本文件

我正在使用$rows = explode("\n", $txt_file);,然後$parts = explode('=', $line_of_text);獲取密鑰名稱和值。但是,我不知道如何處理我不想要的額外信息。

此外,我不知道如何擺脫多餘的空間。該文件似乎是用於某種簡單的解析。我已經遍佈這個網站尋找解決方案。但是,這些數據與我在本網站上找到的示例完全不同。

# This file holds all the timelines available at this time. 
# All lines starting with # is ignored by parser... 
# 

STARTINFO 
description  =  Rubi-Ka 2 
displayname  =  Rimor (Rubi-Ka 2) 
connect   =  cm.d2.funcom.com 
ports   =  7502 
url    =  
version   =  18.5.4 
ENDINFO 

STARTINFO 
description  =  Rubi-Ka 1 
displayname  =  Atlantean (Rubi-Ka 1) 
connect   =  cm.d1.funcom.com 
ports   =  7501 
url    =  
version   =  18.5.4 
ENDINFO 
+4

我已經通過'STARTINFO'分裂和'ENDINFO'適當,然後用['parse_ini_string'](http://www.php.net/manual/en/function.parse-ini-string .php)e – 2013-02-14 13:28:15

回答

1

您可以使用trim函數來消除空白。

爲了只保留你想要的列,你可以將它們的密鑰存儲在一個數組中,並在解析時對它進行檢查。 下面是一個例子(雖然相當詳細)。

<? 
$lines = explode("\n", $data); 
$result = array(); 
$count = 0; 
// an array of the keys we want to keep 
// I have the columns as keys rather then values for faster lookup 
$cols_to_keep = array('url'=>null, 'description'=>null, 'ports'=>null, 'displayname' => null); 

foreach($lines as $line) 
{ 
    //skip comments and empty lines 
    if(empty($line) || $line[0] == '#') 
    { continue; } 

    //if we start a new block, initalize result array for it 
    if(trim($line) == 'STARTINFO') 
    { 
    $result[$count] = array(); 
    continue; 
    } 

    // if we reach ENDINFO increment count 
    if(trim($line) == 'ENDINFO') 
    { 
    $count++; 
    continue; 
    } 

    //here we can split into key - value 
    $parts = explode('=', $line); 

    //and if it's in our cols_to_keep, we add it on 
    if(array_key_exists(trim($parts[0]), $cols_to_keep)) 
    { $result[$count][ trim($parts[0]) ] = trim($parts[1]); } 
} 
print_r($result); 
?> 
+0

太棒了!非常感謝你! – 2013-02-15 19:31:26