如何在 php 变量中包含 php include 语句


How to include a php include statment in a php variable?

我有一个包含html结构的变量,如下所示:

$txt = '<table>
           <tr>
               <td>
              </td>
           </tr>
       </table>';

我想在变量中编写以下语句:

include_once('./folder/file.php');

我尝试像下面这样写它,但它失败了:

$txt = '<table>
               <tr>
                   <td>';
                   include_once('./folder/file.php');
                  $txt.='</td>
               </tr>
           </table>';

我这样尝试,也不起作用:

$txt = '<table>
                   <tr>
                       <td>
                       {include_once('./folder/file.php');}
                     </td>
                   </tr>
               </table>';

我该怎么做?很抱歉,在混合 php 和 html 方面不是很专业,所以一点帮助将不胜感激??

使用输出缓冲区函数:

ob_start();
include('./folder/file.php');
$include = ob_get_clean();
$txt = '<table>
           <tr>
               <td>' . $include . '</td>
           </tr>
       </table>';

见 http://php.net/ob

输出缓冲区收集您发送到浏览器的所有内容,直到您清空、删除或结束它。

http://www.php.net/manual/en/function.ob-get-clean.php

你必须这样做,我相信它被称为连接:

$table_content = include_once('./folder/file.php');
$txt = '<table>
               <tr>
                   <td>
                         ' . $table_content . '
                   </td>
               </tr>
         </table>';

或。。。

$txt = '<table>
               <tr>
                   <td>
                         ' . include_once('./folder/file.php') . '
                   </td>
               </tr>
         </table>';

简单地说,当我需要回显一些文本后跟一个变量时,我的方式是执行以下操作:

$color = brown
$state = lazy
echo "The quick" . $color . "fox jumped over the" . $state . "dog";

这将给出以下结果:

The quick brown fox jumped over the lazy dog

有关详细信息,请参阅: 连接字符串

试试这个

$txt = '<table>
           <tr>
               <td>';
$txt.=include_once('./folder/file.php');
$txt.='</td>
           </tr>
       </table>';
print_r($txt);