【问题标题】:Contents of a file_get_content() to process PHP处理 PHP 的 file_get_content() 的内容
【发布时间】:2014-06-20 02:13:04
【问题描述】:

我需要在使用 file_get_contents(Subfile) 调用模板的文件(子文件)上使用一些 PHP 标记。

我最初使用 require(subFile) 而不是 file_get_contents()。但它并不完全有效,因为我的内容被放置在错误的位置。而且我也无法将模板文件更改为使用 require()。

我的模板是这样的:

//TEMPLATE FILE.php
$html = file_get_contents(subFile); //I CAN NOT CHANGE  THIS FILE

然后是我的子文件,我可以更改的那个。

//SUB FILE.php
<div>Hello world, today is <?php echo date($mydate);?> </div>

因为它是用 file_get_contents() 调用的,所以它会输出

Hello world, today is <?php echo date($mydate);?>

代替:

Hello world, today is Thursday.

所以,考虑到我无法更改使用 file_get_content() 的TEMPLATE FILE.php。 我在想是否有一种方法可以包装 SUB FILE.php 的内容,以便它在允许它被 TEMPLATE FILE.php 调用之前处理 PHP。

我正在追求这样的东西

//SUB FILE.php
<force Process the PHP ?>
<div>Hello world, today is <?php echo date($mydate);?> </div>
<Finishe Force Process ?>
<allow it to be called via file_get_content();

如果我可以更改模板文件,我可以使用 htmlspecialchars_decode();但我不能。

不幸的是,我找不到这样做的方法,所以我最终得到了这个

ob_start();
$output = include (Dir/SubFile);
$output = ob_get_contents();
ob_end_clean();
$html = $output; 

//$html = file_get_contents(subFile); The way it was

【问题讨论】:

  • 可以通过网络服务器访问子文件吗?然后你可以做file_get_contents("http://localhost/subFile.php"); 并且PHP将被执行。
  • 问题是我无法更改发生 file_get_contents() 的模板文件。 :(
  • 那我觉得你倒霉了。您无法通过更改子文件来解决此问题,必须在使用它的脚本中完成。
  • 模板脚本只是读取文件,读取文件并不执行。
  • file_get_contentsrequire 执行两个完全不同的功能。您实际上是在第一个中读取文件的数据,而第二个将传递的文件内容的内容添加为包含它的 PHP。

标签: php file-get-contents


【解决方案1】:

以下为官方手册示例

$homepage = file_get_contents('http://www.example.com');
echo $homepage;

试试这个:

file_get_contents('http://YourDomain/Yoursubfile'); 

【讨论】:

    【解决方案2】:

    您不能使用&lt;?php echo $a; ?&gt; 来回显变量$a 的内容。 因为您将从子文件中获取纯 html 内容。

    你可以做的是:-

    第1步:my_date.php

    <?php
    $today = date('M-d-Y');
    $subfile_html = file_get_contents(subFile);  //Path to my_date1.html or my_date1.php
    echo $new_html_content = str_replace('{TODAYS_DATE}', $today, $subfile_html); // It will replace the occurance {TODAYS_DATE} with today's date
    
    // OUTPUT:
    // Hello world, today is June 20 2014
    ?>
    

    第二步:my_date1.html 或 my_date1.php

    <div> Hello world, today is {TODAYS_DATE} </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 2015-10-19
      • 1970-01-01
      • 2016-08-03
      • 2018-06-09
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      相关资源
      最近更新 更多