56

I want to create a table with <?php ?> script.
How can I insert html code into <?php ?> to achieve my goal?

<?php html code to create table ?>
almaceleste
  • 397
  • 4
  • 11
Karan Bhatia
  • 807
  • 1
  • 8
  • 16

4 Answers4

119

You can do like

HTML in PHP :

<?php
     echo "<table>";
     echo "<tr>";
     echo "<td>Name</td>";
     echo "<td>".$name."</td>";
     echo "</tr>";
     echo "</table>";
?>

Or You can write like.

PHP in HTML :

<?php /*Do some PHP calculation or something*/ ?>
     <table>
         <tr>
             <td>Name</td>
             <td><?php echo $name;?></td>
         </tr>
     </table>


<?php /*Do some PHP calculation or something*/ ?> Means:
You can open a PHP tag with <?php, now add your PHP code, then close the tag with ?> and then write your html code. When needed to add more PHP, just open another PHP tag with <?php.

VC.One
  • 14,790
  • 4
  • 25
  • 57
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • 10
    Second option is *much* better! – Phil Aug 09 '13 at 05:14
  • 1
    Yes @Phil because we can have the more flexible way to add more html.. – GautamD31 Aug 09 '13 at 05:16
  • 2
    What if I want to break my HTML page into multiple parts for convenience e.g. header.php, footer.php. And later include in other pages. For footer, the second method is useless, and first is neither of use. – Santosh Kumar Jun 28 '15 at 03:14
  • 3
    @SantoshKumar did he mentioned to create a separate views? No right..Acc to his question I answered it..And one more thing even if he separated the views the variables will work since we are including the pages..As like we do it Codeigniter – GautamD31 Jun 29 '15 at 04:55
  • Great self-explanatory answer! Thanks! – JustMeh Nov 18 '15 at 11:18
  • What about the `<< – Jurik Apr 05 '16 at 14:02
21

You can drop in and out of the PHP context using the <?php and ?> tags. For example...

<?php
$array = array(1, 2, 3, 4);
?>

<table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>

Also see Alternative syntax for control structures

Phil
  • 157,677
  • 23
  • 242
  • 245
6

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
2

Can place code anywhere

<input class="my_<? print 'test' ?>"  />
Notepad
  • 1,659
  • 1
  • 12
  • 14
  • I know this is WAY late to the party, but this can now be done a little easier this way (IMO): `"; ?>` assuming you have a variable holding `$test`; – jpgerb May 16 '22 at 22:17