在file_put_contents中声明变量时出现问题

时间:2013-07-20 23:19:32

标签: php function

我无法确定如何创建新文件的正确语法,并在文件中放入一系列变量和包含。计划是为一个目录创建索引,该目录知道它所在的目录,理想情况下我希望index.php看起来像这样:

<?php $projectAccess = "Project Name"; ?> <?php include('meta-data.php'); include('header.php'); include('content.php'); include('footer.php'); ?>

我现在一直在努力解决这个问题:这个代码的变化(到目前为止让我最接近):

function indexData($projectAccess) {
   $projectString = "<?php $projectAccess = '" . $projectAccess . "'; ?> ";
   $includes = "<php include('meta-data.php'); include('header.php'); include('content.php'); include('footer.php'); ?>";

   return $projectString . $includes;
}

file_put_contents($path3, indexData($w_title));

但是这会回来:

<?php Project Name = 'Project Name'; ?> <php include('meta-data.php'); include('header.php'); include('content.php'); include('footer.php'); ?>

我希望第一个PHP语句将变量$projectAccess显示为“项目名称”,但它只是迭代字符串而不是将变量放在那里。我知道我在做一些基本错误的事情,请帮忙!

$path3指的是正在创建的文件,这是在脚本中较早确定的,并且是我没遇到的问题,只有indexData()部分很棘手。提前谢谢!

2 个答案:

答案 0 :(得分:2)

你需要逃脱美元符号。

替换此

function indexData($projectAccess) {
   $projectString = "<?php $projectAccess = '" . $projectAccess . "'; ?> ";
   $includes = "<php include('meta-data.php'); include('header.php'); include('content.php'); include('footer.php'); ?>";

   return $projectString . $includes;
}

用这个

function indexData($projectAccess) {
   $projectString = "<?php \$projectAccess = '$projectAccess'; ?> ";
   $includes = "<php include('meta-data.php'); include('header.php'); include('content.php'); include('footer.php'); ?>";
   return $projectString . $includes;
}

另外,请查看manual wrt. how PHP treats double quoted strings

另一件事是$includes - <php的声明中应该有<?php的错误,但为了更好的可读性,可以像这样重写整个:

function indexData($projectAccess) {
    return "
       <?php
           \$projectAccess = '$projectAccess';
           include('meta-data.php');
           include('header.php');
           include('content.php');
           include('footer.php');
       ?>
    ";
}

答案 1 :(得分:0)

对字符串使用单引号。 PHP在单引号内不转换变量。
像这样:

 
function indexData($projectAccess) {
   $projectString = '<?php $projectAccess = "' . $projectAccess . '"; ?> ';
   $includes = "";

   return $projectString . $includes;
}

file_put_contents($path3, indexData($w_title));
 



希望这会有所帮助。