如何从文件中更改变量的值?

时间:2014-07-25 13:13:25

标签: php file

我需要替换file.php中的一行。

我需要替换file.php变量的值,但我可以获得所需的行,获取变量的值,但不知道如何替换整行。

示例:

<?php

    $archive = file('Library/config/PaymentConfig.php'); // transforms the content into an array where each line is a position
    $valueLine = $archive[10]; // $environment = 'production';

    function getEnvironment($valueLine){
        $removecharacters = array('$environment = ', "'", ';');
        return str_replace($removecharacters, '', urldecode($valueLine)); // returns only the value of the variable
    }

    if (getEnvironment($valueLine) == $myValue) { // $myValue = production or sandbox   
        // Here I need to replace the line
        // For $environment = 'production'; or $environment = 'sandbox';
    }

?>

3 个答案:

答案 0 :(得分:1)

根据我的评论,我建议编辑file.php以从txtfile /数据库中获取值。 使用文本文件:

//file.php
$environment = file_get_contents('environment.txt');

然后在您的代码中,您可以更改文本文件中的值:

$environment = 'production';
file_put_contents('environment.txt', $environment);

答案 1 :(得分:0)

正确答案

if (getEnvironment($valueLine) == $myValue) { // $myValue = production or sandbox   
    $archive[10] = '$environment = "sandbox";' . "\n";
    file_put_contents('Library/config/PaymentConfig.php', implode("", $archive));
}

答案 2 :(得分:0)

正确回答2

<?php
    $archive = "Library/config/PaymentConfig.php";
    $search = "PaymentConfig['environment']";
    $arrayArchive = file($archive);
    $position = 0;

    for($i = 0; $i < sizeof($arrayArchive); $i++){      
        if(strpos($arrayArchive[$i],$search) && (strpos($arrayArchive[$i],'production') || strpos($arrayArchive[$i],'sandbox'))){
            $fullLine = $arrayArchive[$i]; // $PaymentConfig['environment'] = "production"; // production, sandbox
            $position = $i;     

            if(strpos($fullLine, '"production"') == true){
                $environment = '"production"';
            } else if(strpos($fullLine, '"sandbox"') == true){
                $environment = '"sandbox"';
            }
        }
    }

    echo $environment; // current environment
    $newEnvironment = '"sandbox"'; // or $newEnvironment = '"production"';

    if ($environment == $myValue) { // $myValue = production or sandbox  
        $arrayArchive[$position] = str_replace($environment, $newEnvironment, $fullLine);
        file_put_contents($archive, implode("", $arrayArchive));    
    }
?>