如何使用php更新ini文件? [英] How to update an ini file with php?
问题描述
我已经创建了一个现有的ini文件,我想知道是否有一种方法可以更新文件的一部分,还是必须每次都重写整个文件?
I have an existing ini file that I have created and I would like to know if there was a way to update a section of the file or do I have have to rewrite the entire file each time?
这是我的config.ini文件的一个示例:
Here is an example of my config.ini file:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
说我要更改[positions] top=false
.因此,我将使用parse_ini_file获取所有信息,然后进行更改并使用fwrite重写整个文件.还是只有一种方法可以更改该部分?
Say I want to change the [positions] top=false
. So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file. Or is there a way just to change that section?
推荐答案
我使用了您的第一个建议:
I used the first suggestion of you:
所以我会使用parse_ini_file获取所有信息,然后进行更改并使用fwrite重写整个文件
So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file
function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
$config_data[$section][$key] = $value;
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}
这篇关于如何使用php更新ini文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!