0

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>

1 Answer 1

3

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();
?>
Sign up to request clarification or add additional context in comments.

2 Comments

i always consider using output buffering a bit of a hack in such cases. but that's just me
@Dagon if you don't use output buffering here the code may become very messy (introducing unnecessary bugs to a perfectly working piece of code), just my view

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.