PHP - Parse ini file and access single values

风格不统一 提交于 2019-12-19 04:02:08

问题


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

myini.ini

[STRINGS]
mystring = fooooo
value = foo_bar

script.py

import configparser
config = configparser.ConfigParser()
# ----------------------------------------------------------------------

config.read("myini.ini")

test = config["STRINGS"]["mystring"]
print (test)      #-> OUTPUT: fooooo

How can I do the same in PHP? Unfortunately, I was not able to find any examples.


回答1:


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


来源:https://stackoverflow.com/questions/34814054/php-parse-ini-file-and-access-single-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!