2010-01-06 54 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 
     ) 

)