0

我很难确定有关如何创建新文件并将一系列变量和包含在文件中的正确语法。计划是为知道它所在目录的目录创建索引,理想情况下我希望 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()部分比较棘手。提前致谢!

4

2 回答 2

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;
}

另外,请查看手册wrt。PHP 如何处理双引号字符串

$includes另一件事是- <phpshould be的声明中存在错误<?php,但整个 this 可以这样重写以获得更好的可读性:

function indexData($projectAccess) {
    return "
       <?php
           \$projectAccess = '$projectAccess';
           include('meta-data.php');
           include('header.php');
           include('content.php');
           include('footer.php');
       ?>
    ";
}
于 2013-07-20T23:23:48.717 回答
0

对字符串使用单引号。当变量在单引号内时,PHP 不会转换它们。
像这样:

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

   return $projectString . $includes;
}

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



希望这可以帮助。

于 2013-07-20T23:43:38.657 回答