Wednesday, December 19, 2007

PHP 5.3 Upgrade: parse_ini_file

I recently started working on a small package to read and write ini files. On the most part PHP does the work for me, as far as parsing ini files goes. Unfortunately parse_ini_files is a bit too intuitive in its approach as it converts some of the original values into other values. These are namely the boolean values. To make matters worse there is not a lot of consistency in the way they are handled. To name an example, there is a different outcome when you use "yes" and "no" values in your ini files: "yes" is converted to "1" but "no" is converted to just "" (empty string) instead of "0" as you would expect.

Because of this behavior, when you read the parsed data from the resulting array you can never know exactly what was in the ini file. Was the original value "yes" or just a numeric value 1. While not an impossible dilemma, it is a bit confusing.

This has been fixed fairly nicely in PHP 5.3, where they added a third argument to the parse_ini_files function, called "scanner_mode" which is represented by the two new constants; INI_SCANNER_NORMAL and INI_SCANNER_RAW. The normal mode is the default and it means the function will work as it always has. But using the raw mode returns the parsed data as-is. It means all section and key names, as well as, values are returned as they exist on the file. This allows you to convert the values into native PHP types more robustly and make a distinct difference between yes/no, 1/0, and true/false values.

At the time I am writing this, the update has not yet reached the PHP manual but it is mentioned in the NEWS file if you download the PHP 5.3 beta.

No comments: