dtcyv3985 2012-05-01 21:15
浏览 98
已采纳

将变量动态更新到现有文件中?

I'm trying to build a small CMS using CodeIgniter, and I need to be able to dynamically update some variables within the application/config.php

So far I did:

private function update_file ($file, $var, $var_name) {
    $start_tag = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
";
    if (file_exists($file)) {
        require_once ($file);
        $updated_array = array_merge($$var_name, $var);         
        $data = $start_tag."\$".$var_name." = ".var_export($updated_array, true).";";
        file_put_contents($file, $data);
    } else {
        return false;
    }
}

Everything works just fine! The result in the config.php file will be:

<?php ...;
$config = array (
'base_url' => '',
...
...
);

But what if I would like to maintain the original config.php file format with comments, spaces and
separated declared $config['key'] = 'value' ... ?

Is that possible ?


EDIT:

Thank you for your answers, very precious. I found a slightly different solution for my needs, performing a preg_replace on the return of file_get_contents() and then write back on the file the new resulting string. File maintains the exact original clean format.

private function update_file ($file, $var, $var_name) {
    if (file_exists($file)) {
        require_once ($file);

        $contents = file_get_contents($file);
        $updated_array = array_merge($$var_name, $var);
        $search = array();
        $replace = array();

        foreach($$var_name as $key => $val) {
            $pattern = '/\$'.$var_name.'\[\\\''.$key.'\\\'\]\s+=\s+[^\;]+/';
            $replace_string = "\$".$var_name."['".$key."'] = ".var_export($updated_array[$key], true);      
            array_push($search, $pattern);
            array_push($replace, $replace_string);
        }

        $new_contents = preg_replace($search, $replace, $contents);
        write_file($file, $new_contents);
}

Maybe it requires some slight performance improvements. But this is my baseline idea.

  • 写回答

2条回答 默认 最新

  • dsfs504545 2012-05-01 21:31
    关注

    It is possible. I can't find the code , but once i have written something like that. Whole idea was based on tokenizing template file and substitute values in an array, preserving key order, line numbers and comments from the template.

    [+] Found it. It's purpose was to fill values from template that looked like this (it was much bigger of course):

    <?php
    
    $_CFG = array(
    
        // DB section
        'db_host' => 'localhost',
        'db_user' => 'root',
        'db_pass' => '',
        'db_name' => 'test',
    
        // Site specific
        'lang' => array('pl','en'),
        'admin' => 'admin@example.com',
    );
    

    And the code that was doing all the magic:

    $tokens = token_get_all(file_get_contents('tpl/config.php'));
    
    $level = -1;
    $buffer = '';
    $last_key = 0;
    $iteration = 0;
    
    foreach($tokens as $t){
        if($t === ')'){
            $iteration = 0;
            $last_key = 0;
            $level--;
        }
    
        if(is_array($t)){
            if($t[0] == T_ARRAY && strtolower($t[1]) === 'array')
                $level++;
    
            if($t[0] == T_CONSTANT_ENCAPSED_STRING){
                if($last_key){
                    if($level){
                        if(isset($new_config[$last_key][$iteration])){
                            $buffer .= var_export($new_config[$last_key][$iteration], TRUE);
                        }
                        else
                            $buffer .= 'null';
    
                        $iteration++;
                    }
                    else{
                        if(isset($new_config[$last_key]))
                            $buffer .= var_export($new_config[$last_key], TRUE);
                        else
                            $buffer .= 'null';
    
                        $last_key = 0;
                    }
                }
                else{
                    $buffer .= $t[1];
                    $last_key = trim($t[1],"'");
                }
            }
            else
                $buffer .= $t[1];
        }
        else
            $buffer .= $t;
    }
    
    file_put_contents('config.php',$buffer);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀