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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?