本文介绍了读写配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



- 附加信息 -



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

解决方案

为此目的,建议使用某种结构化文件格式。

考虑使用,,,或,并使用适当的API来阅读和写他们。



另一个选择是将配置存储在数组中,然后使用 / 或使用 / 使用它。



非常基本例如:

  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;);
}
}

你可以使用这样的类:

  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);


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']?

-- 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.

解决方案

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

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

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);

这篇关于读写配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:07