parse_ini_file

parse_ini_file(string $filename, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false

解析 INI 格式配置文件为关联数组:process_sections 开启分节嵌套,TYPED 模式保留布尔与整数类型,失败返回 false。

C C23

C23
#include <stdio.h>
#include <string.h>

/* 最小 INI 解析器:分节、';' 注释、键值去空白 */
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';
        /* 去尾部回车;跳过空行与 ';' 注释行 */
        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 方言:成对双引号包裹的值要剥引号 */
                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

C++26
#include <iostream>
#include <map>
#include <string>

// 最小 INI 解析器:分节、';' 注释、剥引号
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; // 注释行跳过
        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 方言:剥掉一对包裹的双引号
            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

v11.0.100
// 最小 INI 解析器:分节、';' 注释、剥引号
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; // 注释行跳过
    if (line[0] == '[' && line[^1] == ']')
    {
        section = line[1..^1];
    }
    else
    {
        int eq = line.IndexOf('=');
        var value = line[(eq + 1)..].Trim();
        // INI 方言:剥掉一对包裹的双引号
        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

v1.27.4
package main

import (
	"fmt"
	"strings"
)

func main() {
	// 最小 INI 解析器:分节、';' 注释、剥引号
	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 // 注释行跳过
		}
		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 方言:剥掉一对包裹的双引号
		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

v27.0.1
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // 最小 INI 解析器:分节、';' 注释、剥引号
        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; // 注释行跳过
            }
            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 方言:剥掉一对包裹的双引号
            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

v26.13.1
// 最小 INI 解析器:分节、';' 注释、剥引号
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; // 注释行跳过
  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 方言:剥掉一对包裹的双引号
  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

v8.6.0
// parse_ini_file:从临时文件读固定 INI 样例
$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);
// 默认拍平分节;后面的同名键覆盖前面的
$flat = parse_ini_file($file);
var_export($flat['host']);
echo "\n";
var_export($flat['port']);
echo "\n";
// 开启分节:按节名嵌套的二维数组
$sect = parse_ini_file($file, true);
var_export($sect['database']['name']); // 引号由扫描器剥掉
echo "\n";
// 扫描器保留字规则:true/on/yes -> "1",false/off/no/null -> ""
var_export($sect['debug']['enabled']);
echo "\n";
var_export($sect['debug']['verbose']);
echo "\n";
// TYPED 模式保留真实布尔类型,而不是 "1"/""
$typed = parse_ini_file($file, true, INI_SCANNER_TYPED);
var_dump($typed['debug']['enabled']);
var_dump($typed['debug']['verbose']);
// 文件不存在返回 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

v3.15.2
import configparser

# configparser 是标准库的 INI 读取器(对应 PHP parse_ini_file)
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"))
# 方言差异:configparser 原样保留引号——需要自己剥
name = parser.get("database", "name")
print("name=", name.strip('"'))
# 布尔值在显式调用 getboolean 前一直是字符串
print("enabled=", parser.get("debug", "enabled"), "->", parser.getboolean("debug", "enabled"))
# 不带 fallback 读取缺失键会抛 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

v1.99.1
use std::collections::HashMap;

fn main() {
    // 最小 INI 解析器:分节、';' 注释、剥引号
    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; // 注释行跳过
        }
        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 方言:剥掉一对包裹的双引号
            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

v26.13.1
// 最小 INI 解析器:分节、';' 注释、剥引号
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; // 注释行跳过
  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 方言:剥掉一对包裹的双引号
  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

语言差异说明

C:标准库无 INI 解析器——手写逐行状态机(分节/';'注释/去空白/剥引号);实战用 inih 或 toml++。

C++:同 C 手写;示例演示 trim + 剥引号的最小分节解析,实战惯用 inih/iniparser。

C#:无内置 INI 解析(IConfiguration 的 INI provider 在扩展包);手写最小分节解析或 Microsoft.Extensions.Configuration.Ini。

Go:标准库无 INI 解析——手写逐行状态机;实战惯用 gopkg.in/ini.v1。

Java:java.util.Properties 是无分节的 key=value(也不支持 ';' 注释),分节 INI 需手写;实战惯用 ini4j。

JavaScript:Node 无内置 INI 解析——手写逐行状态机;实战惯用 ini npm 包。

PHP:parse_ini_file 一次成型:process_sections 开分节嵌套;扫描器保留字规则 true/on/yes→"1"、false/off/no/null→""(NORMAL 模式),INI_SCANNER_TYPED 保留真实 bool/int;值含特殊字符必须双引号包裹;不解析 php.ini(运行时值用 ini_get);不可信输入必须 INI_SCANNER_RAW(防止常量插值泄漏);失败返回 false。

Python:configparser 原生读 INI(read_string/read_file);方言差异——引号原样保留(PHP 会剥)、布尔需显式 getboolean;缺失键用 fallback= 回退,否则抛 NoOptionError;另支持 %(name)s 插值(PHP 对应 ${PATH} 环境变量插值)。

Rust:标准库无 INI 解析——手写逐行状态机;实战惯用 configparser 或 rust-ini crate。

TypeScript:同 JavaScript,手写解析或 ini 包。