首页 > 解决方案 > 如何用 fopen 编写变量名称?

问题描述

我正在尝试写入配置文件,但无法打印的问题$names

<?php 
    $myfile = fopen("config.php", "w") or die("Unable to open file!");
    $txt = "$dbname = '1'; $dbuser = '2'; $dbpass = '123'; $dbhost = 'localhost';\n"; 
    fwrite($myfile, $txt); 
    fclose($myfile);
?>

输出显示我

= '1';  = '1';  = '123';  = 'localhost';

我需要他写变量名,需要一些帮助,谢谢!

标签: php

解决方案


您需要转义 $ 符号:

 $myfile = fopen("config.php", "w") or die("Unable to open file!"); 
 $txt = " \$dbname = '1'; \$dbuser = '2'; \$dbpass = '123'; \$dbhost = 'localhost';\n"; 
 fwrite($myfile, $txt); fclose($myfile);

其他明智的使用单引号:

 $myfile = fopen("config.php", "w") or die("Unable to open file!"); 
 $txt = ' $dbname = "1"; $dbuser = "2"; $dbpass = "123"; $dbhost = "localhost";\n'; 
 fwrite($myfile, $txt); fclose($myfile);

说明

php 中的变量 $var 是否在双引号中进行评估,但不是在单引号中。我认为对于表演来说,如果里面的表达式是常量并且不需要评估,那么最好避免使用双引号。


推荐阅读