dqpdb82600 2011-08-25 09:31
浏览 31
已采纳

我可以在PHP中加载一个带有内联变量的字符串吗?

I've got a simple (but not tiny) template for some HTML, complete with inline variables. I'd like to pull that out as a separate file, and have the ability to switch in other template files. Is there a way to load a file into a string, but have it process inline variables?

Eg:

$thing="complete sentence";
$test=<<<END
    This will get parsed as a $thing.
END;
echo $test; // This will get parsed as a complete sentence.

What I want is something like this:

// "test.html"
<html>
<body>
    <p>This will get parsed as a $thing.</p>
</body>

// "index.php"
$thing="complete sentence";
$test=file_get_contents("test.html");
echo $test; // This will get parsed as a complete sentence.

How do I achieve this, preferably without a templating library?

  • 写回答

3条回答 默认 最新

  • dqvs45976 2011-08-25 09:35
    关注

    You can use include to simply load the file as if it were part of the calling code.

    include("included_file.php");
    

    If you cannot include for some reason, you can read the file contents and eval it.

    $content = file_get_contents("included_file.php");
    eval($content);
    

    UPDATE:

    As pointed by NikiC, your file test.html doesn't have valid PHP. You would have to change it so include can work. Your test.html should have this content:

    <html>
    <body>
        <p>This will get parsed as a <?= $thing ?>.</p>
    </body>
    

    And eval would not work with this code, as this is not pure PHP code, it is HTML code with PHP inside it. If your included file has just PHP code, it would work fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:treenode反序列化后获取不到上一节点和下一节点,Fullpath和Handle报错
  • ¥15 一部手机能否同时用不同的app进入不同的直播间?
  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing