Parsing a Configuration File

If you have created a complex application in PHP, you will want to save your data so that you have a persistent store for application configuration options. The Windows .ini file format is a very simple way to store data in a structured manner, and looks like this:

    ; this is a comment

    [Main]
    LastRun = 1076968318
    User = "Paul"

    [Save]
    SavePath = /home/paul
    AutoSave = yes
    SaveType = BINARY

Lines that start with a semicolon (;) and blank lines are ignored. Lines that contain a string surrounded by square brackets, such as [Main] above, are section titles. Sections are just there for organizational reasons, as you will see shortly—above, you can see that the LastRun and User keys are under the Main section, and the SavePath, AutoSave, and SaveType keys are under the Save section.

Each key in the .ini file has a value that follows the equals sign, and the value can either be a string (such as the value for User), a constant (such as the value for AutoSave and SaveType), or a number (such as the value for LastRun). You can use strings without quotes if you want to, as shown in the SavePath value—the quotes are just syntactic sugar that helps differentiate between a string and a constant. However, if your string contains nonalphanumeric characters such as—, the quotes are mandatory to avoid confusion.

Because you can specify strings without quotes, if they are fairly simple strings, the value for SaveType is actually interpreted as a string and sent back ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.