猿问

读写配置文件

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


- 附加信息 -

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


叮当猫咪
浏览 363回答 3
3回答

米琪卡哇伊

建议使用某种结构化文件格式来实现此目的。考虑使用CSV,Ini,XML,JSON或YAML,并使用适当的API来读取和写入它们。另一种方法是将配置存储在一个数组中,然后使用serialize / unserialize或使用var_export / include来使用它。非常基本的例子:class MyConfig{&nbsp; &nbsp; public static function read($filename)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $config = include $filename;&nbsp; &nbsp; &nbsp; &nbsp; return $config;&nbsp; &nbsp; }&nbsp; &nbsp; public static function write($filename, array $config)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $config = var_export($config, true);&nbsp; &nbsp; &nbsp; &nbsp; file_put_contents($filename, "<?php return $config ;");&nbsp; &nbsp; }}你可以使用这样的类: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);

慕莱坞森

使用SQLite。然后,您可以查询特定数据,并且仍然具有本地文件。仅供参考 - PDO报价会自动在值周围添加单引号。$Filename = "MyDB.db";try {&nbsp; &nbsp; $SQLHandle = new PDO("sqlite:".$Filename);}catch(PDOException $e) {&nbsp; &nbsp; 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) {&nbsp; &nbsp; echo $Row["MyColumn"]."\n";}

慕无忌1623718

我同意戈登的观点。如果你不遵循他的建议你可以做这样的事情:$file = file_get_contents('./conf.tpl');$file = str_replace('%server%', 'localhost', $file);file_put_contents('./conf.txt', $file);
随时随地看视频慕课网APP
我要回答