Basel
Basel

Reputation: 1365

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

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 ??

Upvotes: 3

Views: 187

Answers (3)

Pragati
Pragati

Reputation: 16

Try this

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

Upvotes: 0

Daniel W.
Daniel W.

Reputation: 32280

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

Upvotes: 7

AaronHatton
AaronHatton

Reputation: 392

You have to do it as follows i believe it is call concatenating:

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

or...

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

To put it simply when I ever need to echo some text out followed by a variable the way I do it is to do as follows:

$color = brown
$state = lazy

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

This would give the results of:

The quick brown fox jumped over the lazy dog

For more information see: Concatenate Strings

Upvotes: 0

Related Questions