如何使用php更新ini文件?
问题描述:
我有一个现有的ini文件,我已经创建,我想知道是否有方法来更新文件的一部分或我必须每次重写整个文件?如何使用php更新ini文件?
这里是我的config.ini文件的例子:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
说我想改变[positions] top=false
。所以我会使用parse_ini_file来获取所有信息,然后进行更改并使用fwrite来重写整个文件。或者有没有办法改变这一部分?
答
如果您使用PHP INI函数,则必须每次重写该文件。
如果你编写你自己的处理器,你可以(有限制)更新。如果你的插入比你的删除更长或更短,你将不得不重写文件。
答
这是您可以使用正则表达式替换文本字符串的完美示例。检查preg_replace函数。如果你不太清楚如何使用正则表达式,你可以找到一个伟大的教程here
只是为了澄清你需要做这样的事情:
<?php
$contents = file_get_contents("your file name");
preg_replace($pattern, $replacement, $contents);
$fh = fopen("your file name", "w");
fwrite($fh, $contents);
?>
其中$模式是你的正则表达式匹配和$替换是您的替换值。
答
我用你的第一个建议:
所以我会使用parse_ini_file把所有的infromation的然后让我的变化,并使用fwrite来重写整个文件
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);
}
为我工作的魅力..干杯! – irishwill200 2017-06-14 14:30:10