问题
-- Background --
So I am working on a installer script for local dev machines and its for installing word press, What I am trying to do is have it so that the user would select a specific plug in from a drop down box and then from there select which version they want to install.
-- Issue --
So I need to be able to parse the .cfg file and store all the values into variables dynamically so that way if we add more plugins it won't break. How do I go about doing this?
回答1:
Couple of ways, depending on how you wish to store the config data. The fastest way is to store the data as an .ini file and parse it using PHP's built in parse_ini_file. You could also store the data in other formats such as XML and YAML, but I wouldn't recommend XML as you probably won't be transporting the data betweeen disparate systems, also XML tends to be harder to read with all the extraneous tags (vs yaml or ini).
I personally prefer yaml and use Symfony's Yaml Component parser which will parse the yaml file into an array. Symfony's Yaml Component can be used outside of the Symfony framework. You could also look into Zend's Yaml parser as well.
After you pick the format and parser you wish to use, it's as easy as storing the config file somewhere that is accessible by your webserver, requiring it, and passing it through the parser API. After it is parsed you should have access to the values via an array.
-- Update --
<?php
$settings = parse_ini_file('test.ini');
var_dump($settings);
Results:
array(41) {
["plugins"]=>
string(0) ""
["breadcrumb-navxt"]=>
string(5) "4.0.1"
["bp-moderation"]=>
string(5) "0.1.4"
["buddypress-activity-stream-hashtags"]=>
string(5) "0.4.0"
["buddypress-group-documents"]=>
string(5) "0.3.5"
["buddypress-group-email-subscription"]=>
string(5) "2.9.1"
["buddypress-links"]=>
string(3) "0.5"
["buddypress"]=>
string(6) "1.2.10"
["calendar"]=>
string(5) "1.3.1"
["collapsing-pages"]=>
string(5) "0.6.1"
This appears to work as expected, so if I want the version number of the calendar
plug-in I would just do:
var_dump($settings['calendar']);
To store in dynamic variables:
$settings = parse_ini_file('test.ini');
foreach ($settings as $key => $setting) {
// Notice the double $$, this tells php to create a variable with the same name as key
$$key = $setting;
}
var_dump($calendar);
回答2:
Could you store the file in json or php serialised format?
来源:https://stackoverflow.com/questions/10214400/parsing-a-config-file-in-php-to-variables