Mini Mini - 4 months ago 33
PHP Question

Using PHP Function parse_ini_file() on an invalid ini file

I have a ini file comming from an external program, that I have no control over. The ini file does not have double quotes around the values Example:

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


using parse_ini_file() gives me:
syntax error, unexpected ')'

I guess i should read the file raw in php and add double quotes around the values like this:

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


Is this the best practice, and if so how would I do it?

Answer

The INI file format is an informal standard. See https://en.wikipedia.org/wiki/INI_file.
C seems to stand for Comment, but PHP does not understand that. So read the ini file in a string, replace the C with ;, then use 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 )
Comments