在Sh / Bash和php中解析配置参数的最佳/最简单方法
发布时间:2020-12-15 18:31:30 所属栏目:安全 来源:网络整理
导读:我进入了每个php项目(大约25个!),一些sh脚本帮助我完成日常任务,如部署,repo同步,数据库导出/导出等. 对于我管理的所有项目,sh脚本都是相同的,因此必须有一个配置文件来存储依赖于项目的不同参数: # example conf,the sintaxys only needs to be able to h
我进入了每个php项目(大约25个!),一些sh脚本帮助我完成日常任务,如部署,repo同步,数据库导出/导出等.
对于我管理的所有项目,sh脚本都是相同的,因此必须有一个配置文件来存储依赖于项目的不同参数: # example conf,the sintaxys only needs to be able to have comments and be easy to edit. host=www.host.com administrator_email=guill@company.com password=xxx 我只需要找到一种干净的方法,可以从sh脚本中读取(解析)此配置文件,同时,能够从我的PHP脚本中读取这些相同的参数.无需使用XML. 你知道一个很好的解决方案吗? 吉列尔莫
如果您不想像pavanlimo所示那样获取文件,另一个选择是使用循环来引入变量:
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中,相同的基本概念适用: // 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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |