繁体   English   中英

在PHP中包含一个PHP文件

[英]Including a PHP file within PHP

我有一个运行PHP if语句的网站,该语句根据附加的文件类型(例如Jpg,Txt,MP4)显示内容。

所以我显示TXT文件的代码是:

if($post_attachment == 'txt'){$display_attachment = "

        <div class=\"sectionDivide\"></div>
        <div class=\"section\">
            <div class=\"articleAttachment\">
                include(\"../a/files/attachments/$post_year/$post_month/$post_id.$post_attachment\");
            </div>
        </div>

    ";}

问题在于它没有显示TXT文件的内容,而是显示了include("../a/files/attachments/2016/11/161123095119.txt"); 在我的网页上。

如何获取显示$display_attachment的文本文件的内容?

直接(粗略)的方法是使用php的字符串串联运算符( . ):

$display_attachment = sprintf('
        <div class="sectionDivide"></div>
        <div class="section">
            <div class="articleAttachment">' . 
    include("/some/path/to/file") . '
            </div>
        </div>
');

sprintf()的使用虽然不太真正,但仍不太易读,虽然比较混乱,但它却是:

$display_attachment = sprintf('
        <div class="sectionDivide"></div>
        <div class="section">
            <div class="articleAttachment">
%s
            </div>
        </div>
',
    include("/some/path/to/file")
);

一个干净的解决方案将获取包含在字符串变量中的结果并使用它。

显示文件的内容include()是错误的函数。 include()将加载并执行php代码。

您应该尝试使用fread()来获取TXT文件的内容: http : //php.net/manual/en/function.fread.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM