Re-write and close array of a file

10

How do I open a configuration file, re-write the value of an array, and close and save the file? Example: config.php

return Array {
    'DB_TYPE' => 'mysql',
    'DB_USER' => 'root'
}

config.php (After the function is executed):

return Array {
    'DB_TYPE' => 'pgsql',
    'DB_USER' => 'root'
}

Note that DB_USER has not been affected. You could use fopen (), fwrite () and fclose () to do this, but you would lose the other arrays.

The fuelphp framework has this function (save ()): link

I'm not using any framework.

    
asked by anonymous 30.08.2015 / 22:53

6 answers

4

I will divide the answer into three parts: reading the file, modifying it and writing it.

Reading

The require function normally includes a file to run - but if its return is assigned to a variable, it receives the content returned by that file.

File array.php :

return array(
    'DB_TYPE' => 'mysql',
    'DB_USER' => 'root'
);

File index.php :

$array = require('array.php');

Modification

We changed the desired key, as we would normally do:

$array['DB_TYPE'] = 'pgsql';

Writing

Here we will write the configuration file again using the var_export function, which exports a variable in a way that can be understood by PHP. In addition, we have inserted the opening tag and other necessary characters so that there is no syntax error when reading the file again.

file_put_contents(
    'array.php',
    '<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);

So, in the end, the script would look like this:

<?php

$array = require('array.php');
$array['DB_TYPE'] = 'pgsql';

file_put_contents(
    'array.php',
    '<?php' . PHP_EOL . PHP_EOL . 'return ' . var_export($array, true) . ';'
);
    
11.09.2015 / 21:18
2

One of the ways to do this is:

Setting the settings. Where $current_db_type is the line you want to change in the file. And $new_db_type is the change you want to make.

$current_db_type = "'DB_TYPE' => 'mysql'"; 
$new_db_type = "'DB_TYPE' => 'pgsql'";

Then, instantiating SplFileObject to open the file as read

$file = new SplFileObject('config.php', 'r');

Next, starting a variable named output to mount the configuration file line by line, including the changed line.

$output = '';

Next, we will go through the lines of the file and if we find the match between $line and $current_db_type - which is the line we want to change - then change to the values of $new_db_type .

foreach ($file as $line) {
  if (trim($file) == $current_db_type) {
      $line = $new_db_type.PHP_EOL;
  }
  $output .= $line;
}

Lastly, we recorded the changes in the file

$file = new SplFileObject('config.php','w+');
$file->fwrite($output);

Notes:

  • I used Trim to remove the spaces because they make the match crash.
  • Used PHP_EOL to be able to break line. EOL means End Of Line .
  • References: SplFileObject , Foreach , Trim , Predefined Constants

        
    01.09.2015 / 04:27
    0

    This function below searches line by line to string you want and gives replace .

    Do you need a form to make POST too?

    INDEX.php

    <?php
    
        $arquivo = fopen('config.php','r+');
        $string = '';
    
        if ($arquivo) {
            while(true) {
                $linha = fgets($arquivo);
                if ($linha==null) break;
    
                # Busca na linha atual o que vai ser alterado
                if(preg_match("/mysql/", $linha)) {
                    $string .= str_replace("mysql", "pgsql", $linha);
                }else{
                    # Coloca tudo em uma nova string
                    $string.= $linha;
                }
            }
    
            # Move o ponteiro para o início do arquivo
            rewind($arquivo);
    
            # Apaga tudo o que tem no arquivo
            ftruncate($arquivo, 0);
    
            # Reescreve o arquivo
            if (!fwrite($arquivo, $string)) 
                die('Não foi possível atualizar o arquivo.');
    
            echo 'Arquivo atualizado com sucesso';
            fclose($arquivo);
        }
    
    ?>
    

    CONFIG.php

    <?php
    
        return [
            'DB_TYPE' => 'mysql',
            'DB_USER' => 'root'
        ]
    
    ?>
    
        
    11.09.2015 / 13:56
    0

    Speak my friend, yes you can! Using just a few functions is simple.

        public function SetKeywords($Setkeyword, $Setvalue){
            if(gettype($this->words) != 'array'){
                $this->words = array();
            }
            $array = array($Setkeyword => $Setvalue);
            $this->words = array_merge($array,$this->words);
        }
    
        public function ReplaceKeywords($maskContent) {
            if($this->words){
                if(!$maskContent || strlen($maskContent) == 0)
                    return $maskContent;
    
                foreach($this->words as $keyword=>$value)
                {
                    $keyword = '{'.$keyword.'}';
                    $maskContent = str_replace($keyword, $value, $maskContent);
                }
                return $maskContent;
            }
            else
            { 
            return false; 
            }
        }
    
        public function GetReplaceKeywordCount($maskContent){
                if(!$maskContent || strlen($maskContent) == 0)
                    return $maskContent;
                $count = array();
                foreach($this->words as $keyword=>$value){
                    $searchWord = '{'.$keyword.'}';
                    $wordCount = substr_count($maskContent, $searchWord);
                    if($wordCount > 0)
                        $count[$keyword] = $wordCount;
                }
                return $count;
        }
    }
    
    # instancia da classe
    $string = new string;
    
    
    
    # definindo o valor para cada variavel dentro
    # neste exemplo a variavel {DB_TYPE} dentro do arquivo será
    # alterada para MySQL
    $string->SetKeywords('DB_TYPE', 'MySQL');
    $string->SetKeywords('DB_USER', 'root');
    
    
    # aqui você pode abrir o arquivo
    # p.x:
    #
    # file_get_contents(filename)
    
    $arrayConfig = "$configs = [
        'DB_TYPE' => '{DB_TYPE}',
        'DB_USER' => '{DB_USER}'
    ]";
    
    
    
    # aqui a class string irá dar replace nas tag pelo valor definido na função SetKeywords
    $string = $string->ReplaceKeywords($arrayConfig);
    
    # aqui você poderá salvar o arquivo com fwrite()
    echo $string; // return string
    

    In action: link

    This class defines the value for variable, opens the file, takes the contents and the class will go through the string, where it finds the variable will change to the value you set.

    Show!

    Needing a hint, hugs!

        
    13.09.2015 / 06:35
    0

    I would do it as follows.

    Suppose I have the following code:

    return array(
        'nome' => 'Wallace',
        'idade' => '25 anos'
    );
    

    We could get the value of this file and save it in the same script.

    For this we will use include , assigning the return value to the variable. Then we change the value by the variable and save the contents of that variable through the function var_export .

    See:

    $configfile = 'configuracao.php';
    
    $config = include $configfile;
    
    $config['nome'] = 'Wayne';
    
    file_put_contents($configfile, '<?php ' . var_export($config, true));
    

    The var_export will export the value of the variable as a valid PHP code. Note that I used true in the second parameter, so that var_export does not print, but returns the values. So we can save them to a file.

    And the result of the file configuracao.php would be:

    return array(
       'nome' => 'Wayne',
       'idade' => '25 anos'
    );
    
        
    13.09.2015 / 16:37
    -1

    I really found the question a bit confusing, but I'll start, try the following:

    $array=array ('DB_TYPE' => 'mysql', 'PASS'=>'123', 'USER'=>'root');
    

    here change the value:

    $array['DB_TYPE']='pgsql';
    echo $array ['DB_TYPE'];
    
        
    31.08.2015 / 03:40