我如何将ini文件解析为对象

4 php ini

我正在按如下方式获取ini文件的内容

$file = 'config.ini';
if (!file_exists($file)) {
    $file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);
Run Code Online (Sandbox Code Playgroud)

这导致了多维数组,但我宁愿将其作为对象。parse_ini_file()是否可能,我将如何处理?

Cyc*_*ode 6

您可以使用json_encode()json_decode()实现此目的:

$file = 'config.ini';
if (!file_exists($file)) {
  $file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);
// convert to data to a json string
$config = json_encode($config);
// convert back from json, the second parameter is by
// default false, which will return an object rather than an
// associative array
$config = json_decode($config);
Run Code Online (Sandbox Code Playgroud)