Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

php

I have a variable including html structure like following:

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

I want to write the following statement inside the variable :

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

I try to write it like the following but it failed:

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

And I try it like that and also not work:

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

How can I do that? I am sorry not very expert with mixing php and html so a small help will be appreciated ??

like image 355
Basel Avatar asked Jul 07 '26 10:07

Basel


1 Answers

Use Output Buffer functions:

ob_start();
include('./folder/file.php');
$include = ob_get_clean();

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

See http://php.net/ob

The output buffer gathers everything you'd send to the browser until you empty, delete or end it.

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

like image 121
Daniel W. Avatar answered Jul 12 '26 06:07

Daniel W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!