php 读写配置文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2237291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:41:59  来源:igfitidea点击:

Reading and Writing Configuration Files

phpfilevariablesreplace

提问by Gordon

I'm writing a small script which generates some configuration for devices. I want to have separate file, where I'm storing configuration, and change some strings during printing the content of the configuration to the browser. How can I replace string in a line of the file with a variable from $_POST['somevariable']?

我正在编写一个小脚本,它为设备生成一些配置。我想有一个单独的文件,我在其中存储配置,并在将配置内容打印到浏览器的过程中更改一些字符串。如何用 $_POST['somevariable'] 中的变量替换文件行中的字符串?

-- Additional info --

- 附加信息 -

I have several types of devices. I want to have separate file with configuration template for each type of device. If someone want to change configuration of some type device they will change that file not php file. But in order to use this template in php I have to replace some string in that file before printing out to web page, e.g.: sys info hostname %host_name% sys info location %location% ip set %ip% the strings inbetween %% (could be any other) characters should be replaced with $_POST["host_name"], $_POST["location"], $_POST["ip"] etc. All these params gotten from the posted form.

我有几种类型的设备。我想为每种类型的设备提供带有配置模板的单独文件。如果有人想更改某种类型设备的配置,他们将更改该文件而不是 php 文件。但是为了在 php 中使用这个模板,我必须在打印到网页之前替换该文件中的一些字符串,例如: sys info hostname %host_name% sys info location %location% ip set %ip% the strings in between %% (可以是任何其他) 字符应替换为 $_POST["host_name"]、$_POST["location"]、$_POST["ip"] 等。所有这些参数都是从发布的表单中获取的。

回答by Gordon

It is advisable to use a structured file format of some sort for this purpose.
Consider using CSV, Ini, XML, JSONor YAMLand use appropriate APIs to read and write them.

为此,建议使用某种结构化文件格式。
考虑使用CSVIniXMLJSONYAML并使用适当的 API 来读取和写入它们。

Another alternative would be to store the configuration in an array and then either use serialize/unserializeor use var_export/includeto use it.

另一种选择是将配置存储在一个数组中,然后使用序列化/反序列化或使用var_export/ include来使用它。

Very basic example:

非常基本的例子:

class MyConfig
{
    public static function read($filename)
    {
        $config = include $filename;
        return $config;
    }
    public static function write($filename, array $config)
    {
        $config = var_export($config, true);
        file_put_contents($filename, "<?php return $config ;");
    }
}

You could use the class like this:

你可以像这样使用这个类:

MyConfig::write('conf1.txt', array( 'setting_1' => 'foo' ));
$config = MyConfig::read('conf1.txt');
$config['setting_1'] = 'bar';
$config['setting_2'] = 'baz';
MyConfig::write('conf1.txt', $config);

回答by MetaCipher

Use SQLite. You can then query for specific data, and still have a local file. FYI - PDO quote automatically adds single quotes around a value.

使用 SQLite。然后您可以查询特定数据,并且仍然拥有本地文件。仅供参考 - PDO 引用会自动在值周围添加单引号。

$Filename = "MyDB.db";

try {
    $SQLHandle = new PDO("sqlite:".$Filename);
}
catch(PDOException $e) {
    echo $e->getMessage()." :: ".$Filename;
}

$SQLHandle->exec("CREATE TABLE IF NOT EXISTS MyTable (ID INTEGER PRIMARY KEY, MyColumn TEXT)");

$SQLHandle->beginTransaction();

$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue").")");
$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue 2").")");

$SQLHandle->commit();

$Iterator = $SQLHandle->query("SELECT * FROM MyTable ORDER BY MyColumn ASC");

unset($SQLHandle);

foreach($Iterator as $Row) {
    echo $Row["MyColumn"]."\n";
}

回答by pedro

I agree with Gordon.

我同意戈登。

If you don't follow his advice you can do something like this:

如果你不听从他的建议,你可以这样做:

$file = file_get_contents('./conf.tpl');
$file = str_replace('%server%', 'localhost', $file);
file_put_contents('./conf.txt', $file);