简体   繁体   中英

how can I format a generated HTML source code?

this code

$table_rows = '';
foreach ($result as $row) {           
  $tr = '<tr>';
  $tr = $tr . '<td>' . $row['crn_name'] . '</td>';
  $tr = $tr . '<td>' . $row['crn_code'] . '</td>';
  $tr = $tr . '</tr>';            
  $table_rows = $table_rows . $tr;
}

generates this output

<tr><td>forint</td><td>Ft</td></tr><tr><td>euro</td><td>€</td></tr>

It works, but the source code of the page looks terrible. I would like to produce a code which is much more easy to read. Somthing like that:

<tr>
  <td>forint</td>
  <td>Ft</td>
</tr>
<tr>
  <td>euro</td>
  <td>€</td>
</tr>

what should I do?!

Tidy is probably too much. Just use the alternate syntax:

<?php foreach ($result as $row): ?>
  <tr>
    <td> <?= $row['crn_name']; ?> </td>
    <td> <?= $row['crn_code']; ?> </td>
  </tr>
<?php endforeach; ?>

Add suitable whitespace to your output. This is easier if you output your HTML directly and only dip into PHP mode when you need PHP.

<?php foreach ($result as $row) { ?>
<tr>
  <td><?php echo $row['crn_name']; ?></td>
  <td><?php echo $row['crn_code']; ?></td>
</tr>
<?php } ?>

The easiest way to do this without meticulously inserting line breaks, tabs and spaces where they really stick out like a sore thumb would be to use tidy .

    $config = array(
            'indent'         => true,
            'output-xhtml'   => true,
            'show-body-only' => true,
            'wrap'           => false);

    $tidy = new tidy;
    $tidy->parseString($html, $config, 'utf8');
    $tidy->cleanRepair();

您可以使用return \\ r \\ n或换行符\\ n

Yes, you can. Just put teal tab there you want spaces and \\n back each line.

Something like that

$table_rows = '';
    foreach ($result as $row) {           
      $tr = '\n';
      $tr = $tr . '     ' . $row['crn_name'] . '\n';
      $tr = $tr . '     ' . $row['crn_code'] . '\n';
      $tr = $tr . '\n';            
      $table_rows = $table_rows . $tr;
    }

or you can use only space. But \\n <-- for new line. Good luck!

$table_rows = ''; foreach ($result as $row) { $tr = '<tr>\n'; $tr = $tr . ' <td>' . $row['crn_name'] . '</td>\n'; $tr = $tr . ' <td>' . $row['crn_code'] . '</td>\n'; $tr = $tr . '</tr>\n'; $table_rows = $table_rows . $tr; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM