问题描述
我在每一个PHP项目得到了(约25!),一些sh脚本,帮助我与日常任务,如部署,回购同步处理资料,数据库导出/导出等。
I got in every php project (around 25!), some sh scripts that help me with routine tasks such as deployment, repo syncronizing, databases exporting/export, etc.
在sh脚本是所有我管理的项目一样,所以必须有存储取决于项目diferent参数的配置文件:
The sh scripts are the same for all the projects I manage, so there must be a configuration file to store diferent parameters that depend on the project:
# example conf, the sintaxys only needs to be able to have comments and be easy to edit.
host=www.host.com
[email protected]
password=xxx
我只需要找到一个干净的方式在这个配置文件可以从一个sh脚本读取(解析),并在同一时间,能够从我的PHP脚本读取这些参数相同。而不必使用XML。
I just need to find a clean way in which this configuration file can be read (parsed) from a sh script, and at the same time, be able to read those same parameters from my PHP scripts. Without having to use XML.
你知道这个好的解决办法?
Do you know a good solution for this?
吉列尔莫·
推荐答案
如果您不想源文件pavanlimo显示,另一种方法是使用一个循环的变量拉:
If you don't want to source the file as pavanlimo showed, another option is to pull in the variables using a loop:
while read propline ; do
# ignore comment lines
echo "$propline" | grep "^#" >/dev/null 2>&1 && continue
# if not empty, set the property using declare
[ ! -z "$propline" ] && declare $propline
done < /path/to/config/file
在PHP中,相同的基本概念应用:
In PHP, the same basic concepts apply:
// it's been a long time, but this is probably close to what you need
function isDeclaration($line) {
return $line[0] != '#' && strpos($line, "=");
}
$filename = "/path/to/config/file";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
$lines = explode("\n", $contents); // assuming unix style
// since we're only interested in declarations, filter accordingly.
$decls = array_filter($lines, "isDeclaration");
// Now you can iterator over $decls exploding on "=" to see param/value
fclose($handle);
这篇关于解析在SH / Bash和PHP的配置参数的最佳/最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!