parse_ini_file
parse_ini_file(string $filename, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false
Parses an INI config file into an associative array: process_sections nests by section, INI_SCANNER_TYPED preserves bool/int types, and failure returns false.
C C23
#include <stdio.h>
#include <string.h>
/* Minimal INI parser: sections, ';' comments, trimmed key/value */
int main(void) {
const char *ini =
"; app config fixture\n"
"; comments start with a semicolon\n"
"\n"
"[database]\n"
"host = localhost\n"
"port = 5432\n"
"name = \"code abc\"\n"
"\n"
"[debug]\n"
"enabled = true\n";
char section[32] = "";
char line[128];
const char *p = ini;
while (*p) {
const char *nl = strchr(p, '\n');
size_t len = nl ? (size_t)(nl - p) : strlen(p);
if (len >= sizeof(line)) len = sizeof(line) - 1;
memcpy(line, p, len);
line[len] = '\0';
/* strip trailing carriage returns, skip blanks and ';' comments */
if (len > 0 && line[len - 1] == '\r') line[--len] = '\0';
if (len == 0 || line[0] == ';') {
if (!nl) break;
p = nl + 1;
continue;
}
if (line[0] == '[') {
const char *close = strchr(line, ']');
size_t slen = close ? (size_t)(close - line - 1) : 0;
memcpy(section, line + 1, slen);
section[slen] = '\0';
} else {
const char *eq = strchr(line, '=');
if (eq) {
char key[64], value[64];
size_t klen = (size_t)(eq - line), vstart = klen + 1;
while (klen > 0 && line[klen - 1] == ' ') klen--;
memcpy(key, line, klen);
key[klen] = '\0';
while (value && vstart < len && (line[vstart] == ' ' || line[vstart] == '\t')) vstart++;
size_t vlen = len - vstart;
/* INI dialect: surrounding double quotes are stripped */
if (vlen >= 2 && line[vstart] == '"' && line[vstart + vlen - 1] == '"') {
vstart++;
vlen -= 2;
}
memcpy(value, line + vstart, vlen);
value[vlen] = '\0';
printf("%s.%s=%s\n", section, key, value);
}
}
if (!nl) break;
p = nl + 1;
}
return 0;
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
C++ C++26
#include <iostream>
#include <map>
#include <string>
// Minimal INI parser: sections, ';' comments, quote stripping
static std::string trim(const std::string &s) {
size_t b = s.find_first_not_of(" \t");
if (b == std::string::npos) return "";
size_t e = s.find_last_not_of(" \t");
return s.substr(b, e - b + 1);
}
int main() {
std::string ini =
"; app config fixture\n"
"; comments start with a semicolon\n"
"\n"
"[database]\n"
"host = localhost\n"
"port = 5432\n"
"name = \"code abc\"\n"
"\n"
"[debug]\n"
"enabled = true\n";
std::map<std::string, std::string> values;
std::string section;
size_t pos = 0;
while (pos < ini.size()) {
size_t nl = ini.find('\n', pos);
size_t end = (nl == std::string::npos) ? ini.size() : nl;
std::string line = ini.substr(pos, end - pos);
pos = (nl == std::string::npos) ? ini.size() : nl + 1;
line = trim(line);
if (line.empty() || line[0] == ';') continue; // comment line
if (line[0] == '[' && line.back() == ']') {
section = line.substr(1, line.size() - 2);
} else if (size_t eq = line.find('='); eq != std::string::npos) {
std::string value = trim(line.substr(eq + 1));
// INI dialect: strip one pair of surrounding double quotes
if (value.size() >= 2 && value.front() == '"' && value.back() == '"') {
value = value.substr(1, value.size() - 2);
}
values[section + "." + trim(line.substr(0, eq))] = value;
}
}
for (const char *key : {"database.host", "database.port", "database.name", "debug.enabled"}) {
std::cout << key << "=" << values[key] << "\n";
}
return 0;
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
C# v11.0.100
// Minimal INI parser: sections, ';' comments, quote stripping
var ini = """
; app config fixture
; comments start with a semicolon
[database]
host = localhost
port = 5432
name = "code abc"
[debug]
enabled = true
""";
var values = new Dictionary<string, string>();
string section = "";
foreach (var raw in ini.Split('\n'))
{
var line = raw.Trim();
if (line.Length == 0 || line[0] == ';') continue; // comment line
if (line[0] == '[' && line[^1] == ']')
{
section = line[1..^1];
}
else
{
int eq = line.IndexOf('=');
var value = line[(eq + 1)..].Trim();
// INI dialect: strip one pair of surrounding double quotes
if (value.Length >= 2 && value[0] == '"' && value[^1] == '"')
value = value[1..^1];
values[$"{section}.{line[..eq].Trim()}"] = value;
}
}
foreach (var key in new[] { "database.host", "database.port", "database.name", "debug.enabled" })
Console.WriteLine($"{key}={values[key]}");
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
Go v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
// Minimal INI parser: sections, ';' comments, quote stripping
ini := "; app config fixture\n" +
"; comments start with a semicolon\n" +
"\n" +
"[database]\n" +
"host = localhost\n" +
"port = 5432\n" +
"name = \"code abc\"\n" +
"\n" +
"[debug]\n" +
"enabled = true\n"
values := map[string]string{}
section := ""
for _, raw := range strings.Split(ini, "\n") {
line := strings.TrimSpace(raw)
if line == "" || strings.HasPrefix(line, ";") {
continue // comment line
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
section = line[1 : len(line)-1]
continue
}
eq := strings.Index(line, "=")
if eq < 0 {
continue
}
value := strings.TrimSpace(line[eq+1:])
// INI dialect: strip one pair of surrounding double quotes
if len(value) >= 2 && strings.HasPrefix(value, "\"") && strings.HasSuffix(value, "\"") {
value = value[1 : len(value)-1]
}
values[section+"."+strings.TrimSpace(line[:eq])] = value
}
for _, key := range []string{"database.host", "database.port", "database.name", "debug.enabled"} {
fmt.Println(key + "=" + values[key])
}
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
Java v27.0.1
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Minimal INI parser: sections, ';' comments, quote stripping
String ini = "; app config fixture\n" +
"; comments start with a semicolon\n" +
"\n" +
"[database]\n" +
"host = localhost\n" +
"port = 5432\n" +
"name = \"code abc\"\n" +
"\n" +
"[debug]\n" +
"enabled = true\n";
Map<String, String> values = new HashMap<>();
String section = "";
for (String raw : ini.split("\n", -1)) {
String line = raw.trim();
if (line.isEmpty() || line.startsWith(";")) {
continue; // comment line
}
if (line.startsWith("[") && line.endsWith("]")) {
section = line.substring(1, line.length() - 1);
continue;
}
int eq = line.indexOf('=');
if (eq < 0) {
continue;
}
String value = line.substring(eq + 1).trim();
// INI dialect: strip one pair of surrounding double quotes
if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
values.put(section + "." + line.substring(0, eq).trim(), value);
}
for (String key : new String[]{"database.host", "database.port", "database.name", "debug.enabled"}) {
System.out.println(key + "=" + values.get(key));
}
}
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
JavaScript v26.13.1
// Minimal INI parser: sections, ';' comments, quote stripping
const ini = `; app config fixture
; comments start with a semicolon
[database]
host = localhost
port = 5432
name = "code abc"
[debug]
enabled = true
`;
const values = {};
let section = "";
for (const raw of ini.split("\n")) {
const line = raw.trim();
if (line === "" || line.startsWith(";")) continue; // comment line
if (line.startsWith("[") && line.endsWith("]")) {
section = line.slice(1, -1);
continue;
}
const eq = line.indexOf("=");
if (eq < 0) continue;
let value = line.slice(eq + 1).trim();
// INI dialect: strip one pair of surrounding double quotes
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
values[`${section}.${line.slice(0, eq).trim()}`] = value;
}
for (const key of ["database.host", "database.port", "database.name", "debug.enabled"]) {
console.log(`${key}=${values[key]}`);
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
PHP v8.6.0
// parse_ini_file: read a fixed INI fixture from a temp file
$ini = "; app config fixture\n; comments start with a semicolon\n\n[database]\nhost = localhost\nport = 5432\nname = \"code abc\"\n\n[debug]\nenabled = true\nverbose = off\n";
$file = tempnam(sys_get_temp_dir(), 'ini');
file_put_contents($file, $ini);
// Sections flattened by default; later duplicate keys overwrite earlier ones
$flat = parse_ini_file($file);
var_export($flat['host']);
echo "\n";
var_export($flat['port']);
echo "\n";
// With sections: a nested array keyed by section name
$sect = parse_ini_file($file, true);
var_export($sect['database']['name']); // quotes are stripped by the scanner
echo "\n";
// Scanner word rules: true/on/yes -> "1", false/off/no/null -> ""
var_export($sect['debug']['enabled']);
echo "\n";
var_export($sect['debug']['verbose']);
echo "\n";
// TYPED mode preserves real bool types instead of "1"/""
$typed = parse_ini_file($file, true, INI_SCANNER_TYPED);
var_dump($typed['debug']['enabled']);
var_dump($typed['debug']['verbose']);
// A missing file returns false
var_export(parse_ini_file('/no/such/file.ini'));
echo "\n";
unlink($file);
'localhost' '5432' 'code abc' '1' '' bool(true) bool(false) false
Python v3.15.2
import configparser
# configparser is the stdlib INI reader (PHP parse_ini_file counterpart)
fixture = """; app config fixture
; comments start with a semicolon
[database]
host = localhost
port = 5432
name = "code abc"
[debug]
enabled = true
"""
parser = configparser.ConfigParser()
parser.read_string(fixture)
print("host=", parser.get("database", "host"))
print("port=", parser.get("database", "port"))
# Dialect gap: configparser keeps quotes verbatim - strip them yourself
name = parser.get("database", "name")
print("name=", name.strip('"'))
# Booleans stay strings until you call getboolean explicitly
print("enabled=", parser.get("debug", "enabled"), "->", parser.getboolean("debug", "enabled"))
# A missing option without a fallback raises NoOptionError
print("missing fallback:", parser.get("database", "password", fallback="default"))
host= localhost port= 5432 name= code abc enabled= true -> True missing fallback: default
Rust v1.99.1
use std::collections::HashMap;
fn main() {
// Minimal INI parser: sections, ';' comments, quote stripping
let ini = "; app config fixture\n\
; comments start with a semicolon\n\
\n\
[database]\n\
host = localhost\n\
port = 5432\n\
name = \"code abc\"\n\
\n\
[debug]\n\
enabled = true\n";
let mut values: HashMap<String, String> = HashMap::new();
let mut section = String::new();
for raw in ini.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with(';') {
continue; // comment line
}
if line.starts_with('[') && line.ends_with(']') {
section = line[1..line.len() - 1].to_string();
continue;
}
if let Some((key, raw_value)) = line.split_once('=') {
let mut value = raw_value.trim().to_string();
// INI dialect: strip one pair of surrounding double quotes
if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
value = value[1..value.len() - 1].to_string();
}
values.insert(format!("{}.{}", section, key.trim()), value);
}
}
for key in ["database.host", "database.port", "database.name", "debug.enabled"] {
println!("{}={}", key, values[key]);
}
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
TypeScript v26.13.1
// Minimal INI parser: sections, ';' comments, quote stripping
const ini = `; app config fixture
; comments start with a semicolon
[database]
host = localhost
port = 5432
name = "code abc"
[debug]
enabled = true
`;
const values: Record<string, string> = {};
let section = "";
for (const raw of ini.split("\n")) {
const line = raw.trim();
if (line === "" || line.startsWith(";")) continue; // comment line
if (line.startsWith("[") && line.endsWith("]")) {
section = line.slice(1, -1);
continue;
}
const eq = line.indexOf("=");
if (eq < 0) continue;
let value = line.slice(eq + 1).trim();
// INI dialect: strip one pair of surrounding double quotes
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
values[`${section}.${line.slice(0, eq).trim()}`] = value;
}
for (const key of ["database.host", "database.port", "database.name", "debug.enabled"] as const) {
console.log(`${key}=${values[key]}`);
}
database.host=localhost database.port=5432 database.name=code abc debug.enabled=true
Language differences
C: no INI parser in the standard library - hand-write a line-by-line state machine (sections, ';' comments, whitespace trimming, quote stripping); inih or toml++ in real work.
C++: same hand-written approach as C; the example shows minimal sectioned parsing with trim + quote stripping; inih/iniparser are the usual picks.
C#: no built-in INI parsing (the IConfiguration INI provider lives in extension packages); hand-write a minimal parser or use Microsoft.Extensions.Configuration.Ini.
Go: no INI parser in the standard library - hand-write a line-by-line state machine; gopkg.in/ini.v1 is the usual pick.
Java: java.util.Properties is section-less key=value (and has no ';' comments), so sectioned INI needs hand parsing; ini4j is the usual pick.
JavaScript: Node has no built-in INI parser - hand-write a line-by-line state machine; the ini npm package is the usual pick.
PHP: parse_ini_file does it in one call: process_sections nests by section; the scanner treats true/on/yes as "1" and false/off/no/null as "" in NORMAL mode, while INI_SCANNER_TYPED keeps real bool/int types; values with special characters must be double-quoted; it does not parse php.ini (use ini_get for runtime values); untrusted input requires INI_SCANNER_RAW (to block constant interpolation leaks); failure returns false.
Python: configparser reads INI natively (read_string/read_file); dialect gaps - quotes are kept verbatim (PHP strips them) and booleans need an explicit getboolean; missing keys fall back with fallback= or raise NoOptionError; also supports %(name)s interpolation (PHP's counterpart is ${PATH} environment interpolation).
Rust: no INI parsing in the standard library - hand-write a line-by-line state machine; configparser or rust-ini are the usual crates.
TypeScript: same as JavaScript - hand-write the parser or use the ini package.