将数组转换为 .ini 文件 [英] Convert array to an .ini file
问题描述
我需要将一个.ini
文件解析成一个数组,然后更改数组的值并将其导出到同一个.ini
文件中.我设法读取了该文件,但没有找到任何简单的方法将其写回.有什么建议吗?
I need to parse an .ini
file into an array, and later change the values of the array and export it to the same .ini
file.
I managed to read the file, but didn’t find any simple way to write it back.
Any suggestions?
示例.ini
文件:
1 = 0;
2 = 1372240157; // timestamp.
推荐答案
为了将 .ini
文件写回来,您需要创建自己的函数,因为 PHP 没有提供任何函数阅读以外的框(可以在这里找到:http://php.net/manual/pl/function.parse-ini-file.php).
In order to write the .ini
file back, you need to create your own function, for PHP offers no functions out of the box other than for reading (which can be found here: http://php.net/manual/pl/function.parse-ini-file.php).
可能将多维数组封装到.ini
-语法兼容字符串的函数示例可能如下所示:
An example of function that might encapsulate a multidimensional array to .ini
-syntax compatible string might look like this:
function arr2ini(array $a, array $parent = array())
{
$out = '';
foreach ($a as $k => $v)
{
if (is_array($v))
{
//subsection case
//merge all the sections into one array...
$sec = array_merge((array) $parent, (array) $k);
//add section information to the output
$out .= '[' . join('.', $sec) . ']' . PHP_EOL;
//recursively traverse deeper
$out .= arr2ini($v, $sec);
}
else
{
//plain key->value case
$out .= "$k=$v" . PHP_EOL;
}
}
return $out;
}
你可以这样测试:
$x = [
'section1' => [
'key1' => 'value1',
'key2' => 'value2',
'subsection' => [
'subkey' => 'subvalue',
'further' => ['a' => 5],
'further2' => ['b' => -5]]]];
echo arr2ini($x);
(请注意,短数组语法仅从 PHP 5.4+ 开始可用.)
(Note that short array syntax is available only since PHP 5.4+.)
另请注意,它不会保留您的问题中出现的评论.没有简单的方法来记住它们,因为是软件(而不是人类)更新文件.
Also note that it doesn't preserve the comments that were present in your question. There are no easy ways to remember them, when it is software (as opposed to a human) that updates the file back.
这篇关于将数组转换为 .ini 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!