dongyuchen9276 2012-09-10 13:17
浏览 92
已采纳

替换php读取的文件中的变量

I have a small app I am working on that generates configuration files. Because it may be used to generate a few different variants of configurations, I gather the variable values from the user, and then read in a template configuration from a file. That file has the names of the variables in it (i.e. $ip_address) at the proper positions. I have set those variables in my php code before reading and the printing out the files. However, the variable names are printed out, not the values of the variables:

$hostname = $_POST['username'] . "_891";
$domain = $_POST['username'] . ".local";   
$routerFile = "891.txt";

$file_handle = fopen($routerFile, "r");
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   print $line . "<br />";
}

Output example:

hostname $hostname
ip domain-name $domain

How do I get php to replace the variables names with their stored values?

  • 写回答

3条回答 默认 最新

  • dongzhi9192 2012-09-10 13:29
    关注

    I would go this way:

    Create a template with hostname = <?php echo $hostname; ?> lines like so:

    hostname <?php echo $hostname; ?>
    ip domain-name <?php echo $domain; ?>
    

    Then in PHP creating a template You would do:

    ob_start();
    include_once($routerFile);
    $file_output = ob_get_clean();
    

    Now You have the file template filled with the appropriate variables and You can save that file:

    file_put_contents('my_new_router_file.txt', $file_output);
    

    And You should be done.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)