Question

I have this code that produces a table exactly how I want it. I want to put this whole code assigned to a PHP variable e.g.: $table=the posted code. I tried concatenating and heredoc but couldn't get it to output my table as it is when doing and echo $table;. Any input is appreciated

<table id=patients>
    <tr>
        <th>Pt. username</th>
        <th>Pt. number</th>
        <th>Full Name</th>
        <th>Added on</th>
    </tr>


   <?php    $x=1;
   foreach ($users as $patient) {

   ?> <tr <?php if ($x % 2 == 0) {echo "class='alt'"; } ?>>
        <td> <a href="profile.php?username=<?php echo $patient['username'];?>"><?php echo $patient['username'];?></a></td>
        <td> <?php echo $patient['id'];?></td>
        <td> <?php echo $patient['name'];?></td>
        <td> <?php echo $patient['joined'];?></td>
    </tr>

    <?php
       $x++;
        } ?>
</table>
Was it helpful?

Solution

Just use output buffering to put the output into the internal buffer and then capture it.

<?php
  ob_start();
?>
<table id=patients>
    <tr>
        <th>Pt. username</th>
        <th>Pt. number</th>
        <th>Full Name</th>
        <th>Added on</th>
    </tr>


   <?php    $x=1;
   foreach ($users as $patient) {

   ?> <tr <?php if ($x % 2 == 0) {echo "class='alt'"; } ?>>
        <td> <a href="profile.php?username=<?php echo $patient['username'];?>"><?php echo $patient['username'];?></a></td>
        <td> <?php echo $patient['id'];?></td>
        <td> <?php echo $patient['name'];?></td>
        <td> <?php echo $patient['joined'];?></td>
    </tr>

    <?php
       $x++;
        } ?>
</table>
<?php
    $table = ob_get_clean();
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top