Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

python - PHP - Parse ini file and access single values

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...