在file_get_contents中使用插值/变量 - PHP

时间:2017-01-19 22:03:59

标签: php html

我正在建立一个PHP(5.4)网站,我想我会更新PHP代码和网站设计等内容,因此,当我制作一个a时,我不想更改每个文件更新。然后我想如果我使用file_get_contents函数来获取具有导航栏HTML,CSS,JS和PHP代码的文件的内容,并且我在更新中更改了该文件内容,那么它将更容易快点。除了我试图在文件中使用插值的部分中的问题:

PHP中的插值:制作本:

$myVar = "myVarText";
$interpolation_var = "The var \"myVar\" content is : $myvar";
echo $interpolation_var;

返回文字:var“myVar”内容为:myVarText

它只是忽略了它,它也像纯文本一样显示它。我尝试了一切,即便如此:

$file_content = "".file_get_content("path/to/file.txt")."";

因此,如果某人有解决方案,请回答这个问题。

2 个答案:

答案 0 :(得分:0)

使用Output Buffering并使用Error: REBASE: The options argument must contain a context property of type object. Instead, got undefined来继承当前范围内的变量:

include()

答案 1 :(得分:0)

这在我从事项目工作时遇到的有点麻烦。 (我想要一个.html模板转换为.pdf,我可以在浏览器中调试,但也可以在我的PHP代码中使用完全变量插值直接用于html创建的mPdf.Aaaand我不想使用丑陋在html中<?php echo $whatever;>全面使用ob_start(); include("myfile.html"); $var = ob_get_clean();技巧,因为浏览器无论如何都不会在.html文件中呈现php标签。最后请看原文。)

如果你可以改变这个.txt:

The var \"myVar\" content is : $myvar

......那个:

<?php $interpolation_var="The var \"myVar\" content is : $myvar";

这样.txt文件假装是一个vaild .php文件。现在你可以在你的php中使用include / require,你有完整的变量插值:

$myVar = "myVarText";
include "theTxtFile.txt";
echo $interpolation_var;

输出 The var "myVar" content is : myVarText

至于我遇到的原始问题:现在大多数浏览器都会处理生病的html并使用$ vars作为纯文本显示页面

<?php $html="/><!-- This is a little hack to display as pure html for easier debugging but pretend to be a php file with one variable for php includes -->
<!DOCTYPE html>
<html lang='en'>
<head>
 <meta charset='UTF-8'>
 <title></title>
 <style type='text/css'>
 * {outline: 1px solid #f005;}
 </style>
</head>
<body>    
 <p>hello $myvar gets interpolated $thisAlso[red].</p>    
</body>
</html>";

浏览器输出 hallo $myvar gets interpolated $thisAlso[red].

来自html创建的mPdf的php代码。所有变量都经过插值

$mpdf = new mPDF();
$myvar = "apple";
$thisAlso = ["red" => "juice"];
require_once "theHacked.html";
$mpdf->WriteHTML($html);
$mpdf->Output();

Pdf输出 hello apple gets interpolated juice.

相关问题