【发布时间】:2019-06-07 12:37:45
【问题描述】:
我有一个我应该使用 PHP 表单添加的 ini 文件。截至目前,我有工作代码来创建一个不存在的部分,如果存在则替换一个值。我正在努力解决的问题是追加。
例如,这是我现在的 ini 文件。
[Persons]
names = "travis", "jackson"
color = "blue"
在 PHP 方面,我有一个表单来插入节、键和值
假设输入部分是Person,键是color,值是red。
我想要的新ini文件应该是
[Persons]
names = "travis", "jackson"
color = "blue", "red"
我正在尝试修改的原始代码:(taken from this stack article)
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);
}
我的想法只是附加到当前密钥,但我不知道该怎么做
编辑:我尝试过的事情
这对修改前的ini文件进行了零更改
function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
$config_data[$section][$key] = $value;
$new_content = "[$section]\n$value";
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 .= "\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}
这打破了页面
function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
$config_data[$section][$key] = $old_val;
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$old_val, $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);
}
【问题讨论】:
-
那么你有没有尝试过达到你的结果?你有吗,你应该包括那个尝试和结果,以及它与你想要的有什么不同。如果您还没有,您现在应该这样做(理想情况下,在您发布您的问题之前)
-
@PatrickQ 我尝试了几种追加方法,但我只是收到页面错误,我会编辑。
-
附带说明,如果要定期编辑您的“配置”,为什么不使用数据库表而不是文本文件?
-
这是我的导师设置的方式,将这样做是为了获得某些事情的权限。
-
在您的第二次尝试中,您拥有
$config_data[$section][$key] = $old_val;。我没有在任何地方看到$old_val的定义。您如何期望它具有价值?