使用php更改php文件的一部分

时间:2013-10-16 14:44:58

标签: php

我怎样才能只改变一部分php文件。实际上在现有的php文件中添加变量或更改单个变量。我尝试了如下,但这抹去了一切,只回应了“我爱PHP”的文字。

$myFile = '../new_folder_name/index.php'; 
$myContent = 'I love PHP'; 

file_put_contents($myFile, utf8_encode($myContent));

我想添加一个名为$ test的变量,等于10. $test="10";或将现有变量$test更改为10。

2 个答案:

答案 0 :(得分:1)

我用php文件创建php文件

<?php
$dir = "../new_folder_name";

$file_to_write = "index.php";

$content_to_write = '


PHP CODE COMES HERE
$test= GET ('SOMETHING')


';

if( is_dir($dir) === false )
{
mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

fwrite($file, $content_to_write);

fclose($file);

include $dir . '/' . $file_to_write;
?>

我希望每个文件都有一个不同的$ test变量值。我希望在创建文件后能够更改创建文件中变量的值

答案 1 :(得分:0)

尝试使用此功能添加新内容

$myFile = '../new_folder_name/index.php'; 
$myContent = 'I love PHP';
$file=fopen($myFile,"a");
fputs($file,$myContent);
fclose($file);

为了玩变量,我们需要在这里处理一个php文件作为普通文本文件

function get_str_btwn($string, $start, $end)//an function to get string between two string in an string
{
    $string = " " . $string;
    $ini    = strpos($string, $start);
    if ($ini == 0)
        return "";
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
$file=file_get_contents($myFile);
if(substr_count($file,"$myContent"))
$file=str_ireplace(get_str_btwn($file,"$myContent =",";"),"I love PHP",$file);//Assuming format of php file is $myContent is initialized like $myContent="something"; 
else
$file=str_ireplace("<?php","<?php $myContent = 'I love PHP';",$file);

请注意,此代码非常敏感,可能会导致生成的php文件出错,除非您确定php文件的格式,否则不建议常规使用。