May 16, 2008

[php] Clean Code Functions - Clean up your html output from php scripts

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials

free web hosting

[php] Clean Code Functions - Clean up your html output from php scripts

jlhaslip
There is another Topic about writing 'clean' HTML code posted elsewhere on the Forum. I'll edit this Topic and add the link so you can review it on your own, and there is no need for me to comment on it in this thread, but the purpose of this Topic is to introduce a pair of functions which can be used for making sure that the HTML output from my scripts is readable when a view-source is reviewed.

Two handy functions are included here. They work together quite nicely, and I will start this Tutorial with a short summary of the reasons for their 'being'.

Purpose Explained:

For the most part, Web Designers use php as a tool for creating 'dynamic content' on their Web sites. PHP is used to generate the code for a Web Site in HTML (or xml, javascript, etc.). Essentially, the script send off pieces of 'text' which a Browser 'interprets' onto the screen. te text which is sent is (x)HTML, for all intents and purposes. Quite often, the HTML code will send out "<br />" tags for adding a new line of text on the Browser BUT the new line is displayed on the screen only, not in the html code itself. In other words, the source code lists the <br /> tags but the source code is not 'formatted' when you do a view source of the page. So... as a tool for cleaning up the display of the HTML code on a view-source, I often include the following two functions into my scripts to do exactly that.

The first one is for issuing Tabs for indenting blocks of code. The second one injects a new-line control character for a new line.
QUOTE

function tabs($t=1){ // to print $t number of tab characters
for($x = 1; $x <= $t; $x++){
$output .= "\t"; // back-slash t is a tab control character
}
return $output;
}
QUOTE

function nls($n=1){ // to print $n number of new-lines
for($x = 1; $x <= $n; $x++){
$output .= "\n"; // back-slash n is a new-line control character ( \n\r on some systems... Linux or Macs?)
}
return $output;
}

Explanation of the Functions:

The function " tabs" is defined with a default parameter value of "1" which is the default number of tab characters you will include as you use the function. To produce a tabs character in your HTML output, simply call this function in your script as "echo'd" or printed output. the default value is one, but including an integer value as a passed parameter for the function will increase the number of tabs or new-lines in your HTML output.

Examples:
CODE
echo tabs(); // will provide a single tab character
echo tabs(4); // will provide 4 tab characters

Similarly, you can have your HTML output issue a new line by using the
CODE
echo tabs(); // will provide a single new-line
echo tabs(4); // will provide 4 new-lines


Usage:

Here is a sample of a using these functions in a php script to write a readable table :
CODE
<?php

echo nls()'<table>'; // start the table tag on a new line
echo nls(),tabs(1) . '<tr>'; // start the table row tag on a new line with a single tab
echo nls(),tabs(2) . '<td>iterations</td>'; //
echo nls(),tabs(2) . '<td>Interval</td>';   // start the table data tags on a new line with two tabs
echo nls(),tabs(2) . '<td>Average</td>';  //
echo nls(),tabs(2) . '<td>Wait</td>';        //
echo nls(), tabs(1) . '</tr>'; // start the table row end tag on a new line with a single tab
echo '</table>'; // start the table end tag on a new line
echo nls();

?>


I can not emphasis enough that the tabs characters and new lines will affect the view-source output only, not the actual output in your page.

Play with it a little.

*** Note: the tabs characters should be issued AFTER any newlines, or the tabs are effectively added to the previous lines and to not Indent the code in the view-source output properly.
*** Note: HtmlTidy is a script available as an add-on that does an very nice job of formatting the view-source, also. check it out at the Mozilla Extensions Site. It is also a part of the Firebug extension. (I think)

Hope this helps someone, and post any comments you might have about this Tutorial.

 

 

 


Reply

galexcd
Ahh. What a well written tutorial. You've even got the default values for the parameters in the functions. A nice extra touch. I am not a very neat coder, but I may use this script somewhere on the net. But as some of you know I love short code, the shorter the better and if you don't mind I would like to provide a recursion example:

Tabs:
CODE
function tabs($t=1){ // to print $t number of tab characters
return ($t==1)?"\t":"\t".tabs($t-1);
}


Nls:
CODE
function nls($n=1){ // to print $n number of new-lines
return ($n==1)?"\n":"\n".nls($n-1);
}

Reply

jlhaslip
Great modification to that function.

thanks Alex...

Reply

rvalkass
QUOTE
$output .= "\n"; // back-slash n is a new-line control character ( \n\r on some systems... Linux or Macs?)


\n is the control character that represents a linefeed. On Linux and UNIX systems (and a wide array of others), the linefeed character is used to represent a new line. \r is the carriage return character, and is used by Windows in conjunction with the linefeed character to create a new line. The sequence to cause a new line on Windows is in fact \r\n in that order!

The reason \n works on Windows is because it gets translated 'behind the scenes' into the \r\n sequence.

Reply

sad1sm0
I have written myself a function that automatically adds line feeds, but i never thought to do the tabs. That's a good move.

My new line code looks like this


CODE
function writeln($line) {//obviously i stole this from javascript, but i use it in place of echo most of the time.
echo $line."\n";
}


Reply

fffanatics
Very nice tutorial. I have always done something similar but nothing this oop. This tutorial could definitely be expanded into a 'clean' html php class so that one just includes it and uses these functions from that class. I like the tutorial and probably will do something with it in the future.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : , php, clean, code, functions, clean, html, output, php, scripts

  1. How To: Html Tables.
    I find these really useful. (8)
  2. Cakephp On Ubuntu
    using your own public_html folder (0)
    Hi, there are many tutorials about this, but i would like to type the steps i followed in order to
    get cakephp working on my user public_html folder. as many of you probably know, if you have
    apache's userdir module loaded, you can put your web pages on /home/user/public_html , and
    access them with the url: http://localhost/~user/ . I really prefer this, so all my web pages are
    on my personal home, but how to configure cakephp to work with these paths, i got a hard time with
    this, but finally got it!. here's how: in case you don't have apache2's u....
  3. Html Span
    (7)
    HTML Span Description The span tag is quite the handy tag to have at your disposal. You can use
    it for everything from Text Formating, to creating a scrollable text area. When combined with CSS it
    becomes an easy-to-use tool for making your website as uniform as possible, as your not bogged down
    with tags for every heading and title on your website. Try It Out CODE <html>
    <body> <div class="content"> <span class="heading1"> Heading
    or title goes here. </span><br><br> All the content insi....
  4. Html Bdo...
    (13)
    Description I find that it is often difficult to write a sentence backwards, but thanks to HTML, I
    can now complete this task in only a few seconds. Now the only problem is it is very difficult to
    read... Try It Out Welcome to one of the most useless functions of HTML. The tags enable you to
    write a sentence backwards. The code is quite simple. CODE <bdo dir="rtl">I
    find that it is often difficult to write a sentence backwards, but thanks to HTML, I can now
    complete this task in only a few seconds. Now the only problem is it is very difficult to r....
  5. Want-to-start Html Tutorials
    An HTML tutorial that covers the basics (2)
    NOTE: Don't use a rich text editor* for writing HTML code! Use Notepad in Windows,
    SimpleText in Mac or TextEdit in OSX, but you must set the following preferences for the HTML code
    to work! In the Format menu, select Plain Text. Open the preferences window from the Text
    Edit menu, then select "Ignore rich text commands in HTML files." Start Creating Your Own HTML
    File You can either use HTM or HTML file extensions. For more information, visit:
    http://filext.com/file-extension/htm for HTM or http://filext.com/file-extension/html for HT....
  6. Creating Navigation For Html Websites
    Have a common navigation menu for the whole website! (12)
    Pre-requisite: HTML, inline frame tags 1 Attachment(.zip) included. Updates : 29-12-07: Doctype
    added in example files (Advised by jlhaslip) Designing a whole website takes a lot of planning
    and organization. Designing a proper navigation system is a basic step in building your website. If
    you are developing webpages in html you would have observed that as you go on creating pages it
    becomes difficult to maintain the links to the pages. This article will guide you in developing a
    common navigation menu for your website. It describes three ways, so if you don'....
  7. Create A Simple Html Editor With Php And Javascript
    (3)
    Ok, I will teach you how to create a simple HTML editor that runs online with buttons that add HTML
    tags. Before we start: You should have basic knowledge of these languages. HTML/XHTML
    Javascript PHP You will need Ability to use filesystem functions. Chmodding abilities
    Features of Editor Online PHP safe Full HTML support A Few Bad Features Can only create new
    documents or overwrite Fairly unsafe Now we are ready to begin. The PHP Script This will be
    our PHP script that we will use to make the file. Make a file called save.php Here is the....
  8. Nice Clean Php Layout Coding.
    Learn a nice neat way to code your layouts with php (7)
    There are basically two main ways to code your php. Method 1) Creating a php document with an html
    look. The you throw in include tags all over the place. Its unorganized, and you have lots of stray
    files hidden in folders and scattered in your base directory. Its difficult to organize, and you
    make mistakes easily. Example: This document would be called index.php Whatever
    Banner or something Some content here. Mostly along the lines of You might ask what
    the problem was? Well, those include tags tend to multiply, and so do all those unne....
  9. Html Legend
    Learn how to create a handy legend with HTML! (9)
    I think this is pretty neat... good for those people who maybe aren't that great at designing
    things but still want something to look nice.. CODE <fieldset> <legend>Legend
    title</legend> Content </fieldset> try it in note pad.. it looks nice...good for
    forums, sign up forms.......
  10. How To Install Php Scripts
    for people who don't like uploading all the time (0)
    OK. Here's what you need: 1. Web hosting that has FTP 2. A script or something to install 3.
    A program called SmartFTP I'll use my site for an example... 1. Enter your FTP login info
    2. When you login in your files, images, and stuff will show up. 3. Now that you're logged in
    you have to choose what file you want to import into your website. Go to "My Documents" and right
    click on the file you want to put on your site and select "copy". 4. Next you got to open put the
    dictionary that your website is in. Ok what that means the place where the "i....
  11. Spice Up Your Forms
    With a bit of CSS and HTML alignment (11)
    Ever wonder how to make those stylish forms you see everywhere? Well now it's your change to
    learn. This short tutorial will show you how to do exactly that. Here is a bit of css to spice
    up the form. I have included comments to explain what classes will change what in the forms.
    CODE <style type='text/css'> .form table { background-color: #187cae; }
    /*The following css class will change the table cells within the .form div */ .form td {
    background-color: #bbe0f4;            padding: 3px;            border: 0px;         ....
  12. Do You Want To Use Php Code In Your Html Pages?
    Within two minutes you will! (9)
    Whilst searching around for help to setup cutenews blog I came across a way to use php in html pages
    - lo and behold it works! so I thought I'd share it with you all (Unfortunately I can't
    remember the site so I wrote this up a couple of minutes after I did it:) ). This method requires a
    web server with apache installed. So, luckily for us all this covers the whole of Trap17... even
    Qupis /tongue.gif" style="vertical-align:middle" emoid=":P" border="0" alt="tongue.gif" /> Just
    to make the point, this is in no way a difficult task and it doesn't requir....
  13. Ucfirst() And Ucword() Functions In Game Maker
    Just like the PHP functions! (2)
    Hello all! /biggrin.gif" style="vertical-align:middle" emoid=":D" border="0" alt="biggrin.gif"
    /> I have just finished two scripts in GML(Game Maker Language) that I find to be useful: ucfirst()
    and ucwords(). If you have been around PHP for anytime, you probably have run across these
    functions. Simply put, ucfirst() takes the first letter of a sentence and uppercases it. While
    upwords() takes the first letter of every word in a sentence and uppercases it. Nice time-saver for
    stories. /wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" />....
  14. How To Make A Simple File Based Shoutbox Using Php And Html
    (8)
    A simple tut to make a simple shoutbox. Let me jump right in. First of all you need the standard
    equipment for PHP, an IDE like XAMPP and an editor like PHP EDITOR 2OO7. Were going to make a
    simple guestbook using three files, webpage.php, shout.php and shout.txt. Webpage.php can be
    changed to whatver you want, it will be the page on which the guestbok is shown, you could even use
    this code and add it to another php page n your site. Shout.php is the proccessing page and
    shout.txt is where the shouts are stored. Firstly we need to make the visual design of the box.....
  15. Simple Scripts In Html And Javascript
    Things like BackgroundColorChanger and so (7)
    like in the topic, here is a description how to change the Backgroundcolor "On The Fly", by klicking
    on a button or radio-box first, we ned the html-and body-tags, create a new html-file on your
    desktop and write the following: QUOTE <script language = "JAVASCRIPT">
    browser interpretation: html - tag means "hey, browser, here comes HTML" in the body-tag you define
    the looking of your site. you can add things like "bgcolor" for the background, "text" for the
    textcolor and link / alink / hlink / vlink to define the linkcolor ( ) the scripttag i....
  16. Document Type Declarations
    And why we use them in html pages (0)
    This code: CODE <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"> <html> <head>
      <title>HTML 4.0 Strict document</title>     <meta
    http-equiv="content-type"  content="text/html;charset=utf-8" >     <meta
    http-equiv="Content-Style-Type"  content="text/css" > </head>
    <body>      <p>... Your HTML content here ...</p>      <p>... More
    HTML content here ...</p>   </b....
  17. Fast Template Design In Joomla Cms
    Basic knowlege of Html needed (2)
    Joomla is one of the most powerfull CMS sistems around. It is free under GNU/GPL license and
    everyone with simple knowlege of webdesign (and even without it) can use it for it's website.
    For now the only way i know on how to design a template in joomla is by using Dreamweaver and Joomla
    (joomlasolutions1.0.mxp-dreamweaver.mxp) extension for dreamweaver! Template design in joomla
    is quite simple really. This template that i'll show you is the most simplest of them all, but
    it's enough for one to learn Basics of template design. Further notice is that this....
  18. Integrating Html And Css Part 1
    (5)
    Ok. Well i am writing this as a series of tutorials i will be doing on this subject, so enjoy. I
    hope this helps. Introduction to HTML and CSS
    HTML and CSS are to work together. HTML is what puts the characters on the page, while CSS is what
    makes everything look outreageous! For instance, I would use HTML if i wanted to put "Trap17 is
    the poop!" onto my page, although if i wanted to make it look nice like this by adding a font,
    and maybe some color, then I would use CSS. Learn the HTML. Ok this is my lit....
  19. Cpanel Preinstalled Scripts, Extras, And Cpanel Options
    Part 6 of My 7 Part Tutorial (1)
    This Tutorial will be divided into 7 different parts, and this is the first part, when i get the
    other parts together, i will post the links under here /biggrin.gif" style="vertical-align:middle"
    emoid=":D" border="0" alt="biggrin.gif" /> Enjoy. Part 1: E-mail Management Part 2: Useful Site
    Management Tools Part 3: Useful Site Management Tools2.1 Part 4: Analysis/Log Files Part 5:
    Advanced Tools Part 7: Fantastico Detailed Cpanel Tutorial Part 4: PreInstalled Scripts,
    Extra, and Cpanel Options In this tutorial I will, in detail explain all of th....
  20. Fantastico Scripts - A 'how To'
    (0)
    This isnt really a tutorial, more like an idiots guide on how to avoid the problems I encountered
    when setting up my site. This eventually invoved 3 complete reinstalls - you soon learn from your
    mistakes when that happens. I shall use php-nuke as the example here, but it applies to all scripts
    you intend to modify. If you have the disk space available - install your script twice, set up a
    temporary sub-domain for this. The reason for this is you have a full, clean install to go back &
    retrieve any files you may mess up whilst changing code (you will have to do this ....
  21. Your First Autoit
    Learning To Code.. (2)
    Autoit is a simple, yet powerful programming language, it allowed the creation of the pangea
    desktops, and the Remote Pc Control with a cell.. You can learn it too. Here is the first of several
    lessons i will post inside of this topic. It is a 32 bit program, it doesnt work on windows 98, 95,
    and i dont think (THINK) Windows ME Step 1: Download and install the latest version of autoit from
    http://www.autoitscript.com i prefer that you use beta. Step 2: Right click somewhere on your
    desktop or my documents, and mouseover new and click Autoit V3 Script Step 3 (optiona....
  22. How To Create Html Page Anchors
    Click A Link And Take You To A Certin Place On The Same Page (5)
    Have you ever wondered how people have a normal link but all it does it take you to the middle of a
    long page? well here is a solution DEMO: Here Ok well first off for the link it will be just
    like a normal link code except you wont put a http://URL.com/file.php it will look somthing like
    this QUOTE name ">Click This Link! there must be a # sign in front of this to work..
    now, for the content that the person will be re-directed to after clicking the link QUOTE name
    "> the items in bold is what you need to change QUOTE name "> i....
  23. Php Spy Code
    Spy on your site! (21)
    Code Spy Code Description Anyone who comes to ur forum's IP Adress, Site they came From,
    Their Browser and the time they came will get saved in a place that only the admin knows the
    location of... V.2 More features coming up in V.2!!! POst suggestions/problems...
    Preview:- http://s15.invisionfree.com/Spy/index.php ? REFRESH THE PAGE, AND GO HERE:-
    http://h1.ripway.com/programming/spy%20code/spy.html ^^^^^^^That shows all the IP's, Browsers,
    Time, site and stuff....^^^^^^^^ Code First of all, you'll need to host the files.... I sugg....
  24. Css Based Photo Gallery Code
    Fluid design for layout (3)
    Fluid Design Photo Gallery There are quite a few Topics here on the Trap17 Forum about how to
    set-up and use Photo Galleries and about the link code for getting from a Thumbnail Image to a full
    size Image and all that stuff, so I would like to take this "Photo Gallery" concept one step further
    without covering what others have already supplied instruction for. Usually, when there is a
    solution posted here for the code on "how-to-do-this", there are tables involved and the Links are
    placed inside Table cells. Tables are not neccesarilly a bad thing, but they were n....
  25. Multiple Classes In Html
    you can use more than one at a time (8)
    Multiple Classes in Css Styles Classes are used in html pages to give certain defined
    attributes to elements. They are useful when the attributes are to be used in more than one place on
    a page. (Named Id's are only allowed once per page, but I digress... might have a tutorial on
    that some day.) Sometimes you want Red text and sometimes you want Bold text. Easy enough to do,
    simply define a class and apply it to the element you want red or bold. Use this class where you
    want on the page, since classes are enabled to be used in several spots, for different u....
  26. Handy Javascript Code Snips
    Ready to Apply in your webpage (5)
    /tongue.gif' border='0' style='vertical-align:middle' alt='tongue.gif' /> Some common things to
    implement in our webpage very frequently are as follows. How to implement all these I am going to
    tell you in this tutorial. Add To Favorite Set As Homepage Go To Top Of Page No Right Click
    Print Page Adding Current Date Adding Current Time Pop-Up Page Creation Closing Window
    Copyright Notice Updation 01. Add To Favorite Someone may be interested in the content of your
    page. Offer him/her to add the page in his/her favorite menu. To do this you have ....
  27. Basic Html (for Us Kids)
    (23)
    What is HTML? HTML (hypertext markup language) is computer language that is used to webpages. It
    can be confusing to understand for some of us kids. HTML pages are text files that has of HTML tags
    (they can place the text or images whereever you want to place it), and text you can place between
    the tags so the text willshow up on your page when you put it on the WWW. Tags are instructions that
    tell your browser what to show on ya website. They break up your webpage into basic sections. All
    tags start with a (right bracket). If you are a starter you need 4 tools A....
  28. How To Put A Phpbb Login Box On Your Main Site.
    Code and .php included!!! (18)
    I have included my coded file with this... Ok here is the code. CODE // //Create login area,
    replace the phpBB2 in /phpBB2/login.php with your forum's //directory // <form
    action="/phpBB2/login.php" method="post" target="_top"> <table
    width="25%" cellspacing="2" cellpadding="2" border="0"
    align="center">  <tr> <td align="left"
    class="nav"><a href="/phpBB2/index.php" class="nav">Prank Place
    Forum Index</a></td>....
  29. Check Your Scripts
    (4)
    As I am reading through some of the (Mostly PHP) scripts posted here, the following posts are that
    of people saying that the script does not work. I suggest that you should test and make sure that
    your script works BEFORE you post it here. Craig.....
  30. HTML tags and examples
    Condensed form of course from my site... (37)
    Well, I decided to try and help out some of the users here who might be unexperienced in HTML, so I
    condensed the begginer's HTML course at my website. Here it is... Lesson 1 HTML means Hyper
    Text Markup Language. HTML is a very common language used for many websites, is the base for more
    complicated and powerful langauges like php, HTML can seem hard, but you will find it is one of the
    easiest langauges one can learn. The core of HTML is the tag, a tage is just a set of two
    arrows-like brackets created by hitting Shift and the comma key, or Shift and the period....

    1. Looking for , php, clean, code, functions, clean, html, output, php, scripts

Searching Video's for , php, clean, code, functions, clean, html, output, php, scripts
Similar
How To: Html
Tables. - I
find these
really
useful.
Cakephp On
Ubuntu -
using your
own
public_html
folder
Html Span
Html Bdo...
Want-to-star
t Html
Tutorials -
An HTML
tutorial
that covers
the basics
Creating
Navigation
For Html
Websites -
Have a
common
navigation
menu for the
whole
website!
Create A
Simple Html
Editor With
Php And
Javascript
Nice Clean
Php Layout
Coding. -
Learn a nice
neat way to
code your
layouts with
php
Html Legend
- Learn how
to create a
handy legend
with
HTML!
How To
Install Php
Scripts -
for people
who
don't
like
uploading
all the time
Spice Up
Your Forms -
With a bit
of CSS and
HTML
alignment
Do You Want
To Use Php
Code In Your
Html Pages?
- Within two
minutes you
will!
Ucfirst()
And Ucword()
Functions In
Game Maker -
Just like
the PHP
functions
3;
How To Make
A Simple
File Based
Shoutbox
Using Php
And Html
Simple
Scripts In
Html And
Javascript -
Things like
BackgroundCo
lorChanger
and so
Document
Type
Declarations
- And why we
use them in
html pages
Fast
Template
Design In
Joomla Cms -
Basic
knowlege of
Html needed
Integrating
Html And Css
Part 1
Cpanel
Preinstalled
Scripts,
Extras, And
Cpanel
Options -
Part 6 of My
7 Part
Tutorial
Fantastico
Scripts - A
'how
To'
Your First
Autoit -
Learning To
Code..
How To
Create Html
Page Anchors
- Click A
Link And
Take You To
A Certin
Place On The
Same Page
Php Spy Code
- Spy on
your
site!
Css Based
Photo
Gallery Code
- Fluid
design for
layout
Multiple
Classes In
Html - you
can use more
than one at
a time
Handy
Javascript
Code Snips -
Ready to
Apply in
your webpage
Basic Html
(for Us
Kids)
How To Put A
Phpbb Login
Box On Your
Main Site. -
Code and
.php
included!
;!!
Check Your
Scripts
HTML tags
and examples
- Condensed
form of
course from
my site...
advertisement



[php] Clean Code Functions - Clean up your html output from php scripts



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE