【问题标题】:Include parts of table in separate php file在单独的 php 文件中包含表的部分内容
【发布时间】:2012-10-24 04:07:57
【问题描述】:

我希望能够将 HTML 表格的某些部分包含在单独的 php 文件中。因此,例如,我可能有一个这样的表:

<table>
<tr><td>Pos.</td><td>No.</td><td>Driver</td><td>Car</td><td>Points</td></tr>
<tr><td>4.</td><td>77</td><td>Andrew Jordan</td><td>Honda Civic</td><td>346</td></tr>
</table>

我想做的是只提取 pos、driver 和 points 的单元格,以便可以在不同的 php 文件中呈现表格,而不必每次都手动复制和编辑。

<table>
<tr><td>Pos.</td><td>Driver</td><td>Points</td></tr>
<tr><td>4.</td><td>Andrew Jordan</td><td>346</td></tr>
</table>

是否可以使用“类”或 php 的“包含”来做到这一点?我知道你可以包含整个 php 文件,但是提取文件的特定部分呢?

【问题讨论】:

  • 我强烈建议您开始在模型视图控制器框架中编码,快速的 google 搜索将为您提供大量有用的信息。简而言之,MVC 的主要目的是将您的模板与您的逻辑分开,这反过来又允许您在需要时访问您的模板或模板的一部分,而无需重写任何 html。

标签: php file include extract


【解决方案1】:

table.php

$table = "<table>
<tr><td>Pos.</td><td>Driver</td><td>Points</td></tr>
<tr><td>4.</td><td>Andrew Jordan</td><td>346</td></tr>
</table>";

table2.php

include("table.php");

print $table;

【讨论】:

    【解决方案2】:

    如果你想有一个可重用的代码来生成这样的部分输出,你可以考虑使用输出缓冲。

    写一个这样的函数:-

    function get_output($file_name,$parameters = NULL)
    {
    include $filename;
    ob_start();
    
    //The included file generates the output required using $parameters
    
    return ob_get_clean();
    }
    

    然后在你使用的主文件中:-

    $output = get_output($file_name,$parameters);
    echo $output; // gives the output generated inside get_output function
    

    在您的情况下,只需将代码存储在一个文件中,例如“table.php”,然后

    $output = get_output('table.php',NULL);
    

    reference

    【讨论】:

      猜你喜欢
      • 2013-06-24
      • 2011-11-30
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2013-03-19
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多