2010-01-06 53 views
1

我有一個像這樣的配置文件:http://pastie.org/768582,我的目標是在數組中獲取每個鍵的註釋和鍵/值。在php中解析配置文件的算法(Doxygen文件)

array( array(

'comment' => "The PROJECT_NAME tag is a single", 

    'key' => "PROJECT_NAME", 

    'value' => "JMK", 
), 

)

我會知道是什麼algoritm我必須使用?

我已經使用explode()函數將配置文件的內容轉換爲數組(逐行)。

現在我正在嘗試獲取所有註釋行,而下一行以'#'開頭,而且還有兩個鍵/值,但在這裏我遇到了麻煩。

如果有人有一個想法,這將是很好的。謝謝。

回答

0

您可以嘗試parse_ini_file(),格式看起來是兼容的。但它不會處理評論。

+0

不幸的是,文件似乎並不格式正確。請參閱評論'#'而不是';'第一個特殊字符'('輸出一個錯誤,我想我會這樣做 – toddoon 2010-01-06 16:12:09

+0

Infact doxygen配置文件看起來與Makefile相似,我會看看PHP是否可以輕鬆解析Makefile。 – toddoon 2010-01-06 16:17:34

1

這將讓你的鍵/值對,而不是評論:

$options = array(); 

foreach ($line as $l) 
{ 
    $l = trim($l); 
    if (strlen($l) && substr($l, 0, 1) != '#') 
    { 
    list($key, $value) = explode("=", $l); 

    // remove whitespace from the end of the config key 
    $key = rtrim($key); 

    $options[$key] = $value; 
    } 
} 
1

這裏有一個方法

$content = file_get_contents("file"); 
$s = preg_split("/#--*/",$content); 
$y = preg_split("/\n\n/",end($s)); 
for($i=0;$i<count($y)-1;$i++){ 
    if ($y[$i]){ 
     if (strpos($y[$i],"#")!==FALSE){ 
      $comment="$y[$i]\n"; 
      $conf=$y[$i+1]; 
      $cs = array_map(trim,explode("=",$conf)); 
      $A["comment"]=$comment; 
      $A["key"]=$cs[0]; 
      $A["value"]=$cs[1]; 
      $TA[]=$A; 
     } 
    } 
} 
print_r($TA); 

輸出

Array 
(
    [0] => Array 
     (
      [comment] => # This tag specifies the encoding used for all characters in the config file 
# that follow. The default is UTF-8 which is also the encoding used for all 
# text before the first occurrence of this tag. Doxygen uses libiconv (or the 
# iconv built into libc) for the transcoding. See 
# http://www.gnu.org/software/libiconv for the list of possible encodings. 

      [key] => DOXYFILE_ENCODING 
      [value] => UTF-8 
     ) 

    [1] => Array 
     (
      [comment] => # The PROJECT_NAME tag is a single word (or a sequence of words surrounded 
# by quotes) that should identify the project. 

      [key] => PROJECT_NAME 
      [value] => JMK 
     ) 

    [2] => Array 
     (
      [comment] => # The PROJECT_NUMBER tag can be used to enter a project or revision number. 
# This could be handy for archiving the generated documentation or 
# if some version control system is used. 

      [key] => PROJECT_NUMBER 
      [value] => 10 
     ) 

)