I have been confused about this question for a long time. I hope someone can give me some advice.
If the content in config.php is:
<?php
$config['heelo'] = array(
'k1' => '111111',
'k2' => '222222',
'k3' => '333333',
);
or it could be:
<?php exit;?>{
"k1": "111111",
"k2": "222222",
"k3": "333333",
}
How should I modify the value under 'k1'? How can I achieve this without using str_replace? (Because the value of 'k1' is not fixed, the method I want is to find the key, then modify the value of the key and save the file)
大家讲道理2017-07-03 11:42:50
The first one is easier to do, but the second one should be checked first to see if it is written correctly. This structure is similar to a JSON object but not, so it is not easy to do.
The first method
include '....'; // 此处为文件名
// 下面只是示例,随便怎么操作$config['hello']
foreach($config['hello'] as $key => $value) {
...
}
$output = "$config['hello'] = " . var_export($config['hello'], TRUE);
file_put_contents('....', $output); // 省略号处为原来的文件名
Mainly use var_export
to output an array that can be read by PHP. When the second parameter of this function is false
, it will be output directly. When it is true
, the result will be returned to the variable.
One thing that needs to be reminded is that the array layout generated by this function is not very good-looking. If you mind, just write one yourself.
Modify the example code of k1
include '....';
$config['hello']['k1'] = 'aaaa';
$output = "$config['hello'] = " . var_export($config['hello'], TRUE);
file_put_contents('....', $output);
漂亮男人2017-07-03 11:42:50
In fact, the easiest way is not to write the config file like this. The config file format is generally as follows:
<?php
return [
'k1' => '111',
'k2' => '222',
'k3' => '333'
];
External files can directly assign the value of the array to a variable by requiring the file, such as
$config = require 'config.php';
It’s easy to get and change values, and it’s also easy to write back to files.