PHP - Parse ini file and access single values

前端 未结 2 1519
Happy的楠姐
Happy的楠姐 2020-12-16 07:57

In Python you can parse an .ini file and access the single values like this:

myini.ini

[STRINGS]
mystring = fooooo
valu         


        
相关标签:
2条回答
  • 2020-12-16 08:18

    Not to fear, parsing an .ini file is a standard method. (See parse_ini_file in the php docs).

    Using your file as the base of this example:

    myini.ini

    [STRINGS]
    mystring = fooooo
    value = foo_bar
    

    test.php

    $ini_array = parse_ini_file("myini.ini");
    print_r($ini_array); # prints the entire parsed .ini file
    
    print($ini_array['mystring']); #prints "fooooo"
    

    Note that by default parse_ini_file ignores sections and gloms all ini settings into the same object. If you'd like to have things scoped sectionally as in your python example, pass true for the process_sections parameter (second parameter).

    test2.php

    $ini_array = parse_ini_file("myini.ini", true /* will scope sectionally */);
    
    print($ini_array['mystring']); #prints nothing
    print($ini_array['STRINGS']['mystring']); #prints fooooo
    
    0 讨论(0)
  • 2020-12-16 08:18

    From the intermediate approach, to get match section, it needs to read any INI file from line to line, in this case you can use fgets function or stream_get_line function to read for each line until the section founded or end of file (not founded).

    Inside every line we can use preg_match (using regex pattern) that match with the actual section name been searched.

    The essential of this approach is to reduce memory usage meanwhile many concurrent request occurs at the same time, so in this case we use string object with any sufficient length as a buffer.

    Good luck Buddy.

    0 讨论(0)
提交回复
热议问题