在无效的ini文件中使用PHP函数parse_ini_file()

时间:2016-07-03 18:38:30

标签: php parsing ini

我有一个来自外部程序的ini文件,我无法控制。 ini文件的值没有双引号示例:

[Setup]
C SetupCode=Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters.

使用parse_ini_file()给我:syntax error, unexpected ')' 我想我应该在php中读取原始文件并在这些值周围添加双引号:

[Setup]
C SetupCode="Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters."

这是最佳做法,如果是这样,我该怎么做?

1 个答案:

答案 0 :(得分:3)

INI文件格式是非正式标准。存在变化,请参阅https://en.wikipedia.org/wiki/INI_file C似乎代表评论,但parse_ini_file()并不理解。因此,请在字符串中读取ini文件,将C替换为;,然后使用parse_ini_string()

<?php
// $ini_string = file_get_contents(...);

// test data
$ini_string = "
[Setup]
C SetupCode=Code of the currently installed setup (JOW
C machine configuration). Use a maximum of 8 characters.
SetupCode=my C ode
";

// replace 'C ' at start of line with '; ' multiline
$ini_string = preg_replace('/^C /m', '; ', $ini_string);

$ini_array = parse_ini_string($ini_string);


print_r($ini_array); // outputs Array ( [SetupCode] => my C ode )