我有一个文档(doc1),它是一个HTML / PHP网站,带有一个“密钥”,可作为占位符来替换文本。 我还有第二个文档(doc2),我想用另外几行代码显示doc1。 当前是doc2代码: 因此,如果我正在处理基本的HTML文件,但是如果我对PHP文件使用此方法,则此代码将无法呈现。我该如何更改才能使doc1代码呈现? 答案 0 :(得分:1) 如果您在代码中执行此操作,则确实会完全遗漏PHP的要点,因为PHP最初是作为模板语言创建的。它打算以一种优雅而流畅的方式解决您现在要解决的问题。与您现在尝试的僵化和过度设计的方式不同。 如果您的文档是完整的PHP代码,则只需将 您完成了! 要进行详细说明,只要通过HTML运行纯HTML或PHP文件,它们就可以正常工作。假设您有一个像 现在 通过PHP运行 根据您的问题, 精确 是您追求的目标:) 答案 1 :(得分:-2) 要合并并执行PHP文件,您需要使用 <?php
$file = "doc1.php";
$key = "<!-- Placeholder -->";
$appcode = '!-- Replaced text -->
<link rel="stylesheet" type="text/css" href="newcode.css">
<script src="newcode.js"></script>
<script>
newCode();
</script';
$index = fopen($file, "r") or die("Unable to open doc1.php");
$code= fread($index,filesize("doc1.php"));
fclose($index);
$index_replaced = (preg_replace ($key, $appcode, $code));
echo($index_replaced);
?>
2 个答案:
<!-- Placeholder -->
替换为<?=$placeholder?>
,现在就可以在doc2脚本中执行以下操作以正确呈现它... <?php
$placeholder = <<<'EOT'
<link rel="stylesheet" type="text/css" href="newcode.css">
<script src="newcode.js"></script>
<script>
newCode();
</script'
EOT;
include 'doc1.php';
doc1.php
这样的文档,如下所示... <html>
<?=$tag?>
<body>
<h1>Hello PHP!</h2>
</body>
</html>
doc2.php
中,您有... <?php
$tag = <<<'EOT'
<title>This is how templating is done</title>
EOT;
include 'doc1.php';
doc2.php
时,您将得到如下最终输出... <html>
<title>This is how templating is done</title>
<body>
<h1>Hello PHP!</h2>
</body>
</html>
include
或require
。您可以使用输出缓冲区功能来捕获结果。ob_start();
require($file);
$code = ob_get_clean();
$index_replaced = preg_replace($key, $appcode, $code);
echo $index_replaced;