一、原想法:一直觉得parse_ini_file效率会比使用require一个数组array差
针对ini格式的txt文件(PHP程序开发中框架的配置文件喜欢使用这种格式),php有一个自带的函数:parse_ini_file来解析成数组。
但我原来一直觉得这样效率会比使用require一个数组array差,毕竟需要将字符串转化成数组。
二、对比测试:简单调用10000次统计消耗时间来对比
但我今天做了次对比。结果完全不是我想你地那样,结论是:parse_ini_file 解析的速度绝对比 require 一个数组php文件要快。
以上是测试的程序代码,很简单使用10000次统计时间查看。结果如下:
三、parse_ini_file 方法详细了解
可见 parse_ini_file 这个函数很有作用,也建议大家在开发程序的时候推荐作用 ini 文件进行配置。
而目前我在很多PHP框架里我们会看到很多PHP格式的配置文件,里面大都是return 一个array,不过也有一些地方我们会碰到一些 ini 配置文件,里面的配置格式示例:
[common]
url = http://47.3.1.36
key = w23n35n2mhk3213uiy34hich
[account]
username = linge
password =ew8912kllw90ew1
那我们会想,到底是通过怎样的加载方式,把这个文本文件加载成PHP数组的呢?你也许会飘过一个想法,难道使用PHP对这整个字符串进行截取切割处理么?这样效率当然很低,那使用PHP对每行进行处理么?也一样是一个性能很低下的表现,实际上PHP本身的ini配置文件(php.ini)就是这样的格式的,那PHP用什么方法加载这样的配置文件呢?
parse_ini_file 方法:这个方法一步就能把整个ini文件整理并返回数组,
parse_ini_string ( string $ini [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )
parse_ini_string() returns the settings in string ini in an associative array. The structure of the ini string is the same as the php.ini's.
parse_ini_file 这个函数是在php5.3时引入的函数,我看到有的网站里的配置文件的值都加上了双引号,我自己尝试了一下,不加引号也基本没问题的。不过在有些情况下会出问题,值之间有空格并且留出了“ true ”," yes "等等这些boolean值时就会报错的,例如上面的配置文件如改成下方配置:
[common]
url = http://47.3.1.36 yes
则在执行的时候就会报语法错误:Warning: syntax error, unexpected BOOL_TRUE in
后来看手册有提示:
As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible.
四、关于另一个解析 ini 文件的方法 parse_ini_string
除了上面介绍的这个 parse_ini_file 方法之外,PHP里其实还有一个方法可以对 ini 配置文件进行解析。那就是:parse_ini_string
但 parse_ini_string 和上面的功能其实是一样的,只不过是上面的方法需要传入 file 的路径为参数,而 parse_ini_string 方法需要传入 ini 配置文件内容。相当于在中间要自己手动获取一步 file 的文件内容。
这样来看,还是建议优先使用 parse_ini_file 更简洁,效率会更高。