Log in

View Full Version : Formatting HTML code using PHP



jdadwilson
11-03-2015, 05:39 PM
I assume this is a very basic question but I am not able to find a solution.

I have used PHP for the past several years and am mostly proficient in its use. My problem is that when I "view source" the html created from the PHP is not structured/formatted like stand-alone HTML (i.e., long lines with no returns). What must one do in the PHP code to cause the resultant PHP created HTML code to appear normal.

TIA for any assistance
jdadwilson

Beverleyh
11-03-2015, 06:10 PM
Is this what you mean?
<?php

echo "<table>
<tr>
<td>Hello</td>
</tr>
</table>\n";

?>

jdadwilson
11-03-2015, 06:50 PM
Somewhat, but not exactly...

My coding is generally to let PHP do its thing but then convert back to HTML for the output rather than using echos for the PHP. Example...



<div class="Letters" id="Table-<?php echo $letter;?>" style="display:none;">
<h3>Family Pages for letter - <?php echo $letter;?></h3>
<ul class="list_links"><?php
while ($rec_Fam = $query_PDO->fetch(PDO::FETCH_ASSOC)) {?>
<li><a href="familypages.php?fam_ltr=<?php
echo $letter;?>&amp;fam_ID=<?php
echo $rec_Fam['fam_id'];?>"><?php
echo $rec_Fam['fam_name_short'];?></a>
</li><?php
}?>
</ul>
</div><?php


The above code generates multiple line of HTML but with no structure. (see the source on this link: http://www.txfannin.org/new-site/familypages.php. Specifically note the <li> code.).
It seems that even straight HTML code which is interrupted with PHP gets messed up. (note div for container-fluid followed by div for panel [looks good] but then the div for the page-header [which is preceded by PHP code] is no longer formatted properly).

Is it as simple as adding an echo "\n"; after selected changes to PHP (e.g., </li><?php echo "\n";)?

Thanks for your assistance
jdadwilson

Beverleyh
11-03-2015, 08:29 PM
You can echo tabs and new lines to create the indented code (see my previous demo for an example for reference). It's easier to manipulate if you put the echo at the start of the line an then add the tabs ahead of whatever variable you're echoing (again, see how the demo has the echo right up to the left, followed by tabs, before the HTML).

\n is like a new line - it's an escape character with special meaning so it must be enclosed in double-quotes for it to become a line feed.

Put it in single-quotes and it will be interpreted as a literal string instead. More info along with other special escape characters here http://php.net/manual/en/language.types.string.php