Jump to content
xisto Community
vujsa

Rapid HTML code generation using simple PHP avoid those repetative boring tasks....

Recommended Posts

I don't know about the rest of you, but I love writting scripts but hate WRITTING scripts.

For example, how many times do you think you have typed the following.

Example #1:

<INPUT TYPE="TEXT" NAME="Foo" VALUE="Foo Value" SIZE="25" MAXLENGTH="100">

Select fields are worse, especially if you write clean code like I do with indents and seperate lines for each tag.

Example #2:

<SELECT NAME="Fruits">    <OPTION>Apples</SELECT>    <OPTION SELECTED>Oranges</SELECT>    <OPTION>Grapes</SELECT>    <OPTION>Peaches</SELECT></SELECT>

Having been writting HTML for 10 years now, so I look for as many shortcuts as possible. Now I let PHP write all of the repetitive HTML and I just fill in the blanks.

From Example #1, all we needed was the information in the quotes: "TEXT", "Foo","Foo Value","25","100"

Everything else is just adding to your carpal tunnel syndrom. so lets get rid of it!

 

You'll need a function:

Function #1:

<?function build_input_field($type,$name,$value,$size,$maxlength) {    $field = "<INPUT TYPE=\"$type\" NAME=\"$name\" VALUE=\"$value\" SIZE=\"$size\" MAXLENGTH=\"$maxlength\"><BR>\n";    return $field;}?>

Now call your function.

Call #1:

<? build_input_field("TEXT","Foo","Foo Value","25","100"); ?>

The above would automatically create the code for example #1.

 

Now adding your own formating to the function will allow you to output code exactly the way do needed it.

 

Building a select field requires a little more effort. I had originally considered simply explaining the the differences between writting the code for an input field and a select field and referencing the previous Function and Call. But after some thought, I reallized that for most beginners the loops, call, arrays, and conditions needed in unison may prove to be too confusing. So I'll expain how the entire process works for the script I wrote to build select fields from a one line call embedded in standard HTML.

 

Let's revisit example #2

Example #2:

<SELECT NAME="Fruits">    <OPTION>Apples</SELECT>    <OPTION SELECTED>Oranges</SELECT>    <OPTION>Grapes</SELECT>    <OPTION>Peaches</SELECT></SELECT>

In Example #2 the required information is:

Field Name -> "Fruits"

Options -> "Apples, Oranges, Grapes, Peaches"

Selected Option -> "Oranges"

 

We have three main arguments for our function a four secondary arguments. for the Options argument.

 

Looking at the Options argument, it looks very similar to an array.

$options = array("Apples","Oranges","Grapes","Peaches");

 

So our call should look something like this:

Specific:

<? build_select_field("Fruits",array("Apples","Oranges","Grapes","Peaches"),"Oranges"); ?>

 

General:

<? function_name("Field_Name",array("Option1","Option2","Option3","Option4"),"Option Selected"); ?>

 

Now that we have a Call, we can write a function that can convert the Call into usable HTML.

 

Writing the function.

Step 1 - Name your function and list arguments.

function build_select_field($name,$select_array,$selected) {

 

Step 2 - Start writing select field code.

Simply define a variable to hold the first line of the select field code.

$select = "<SELECT NAME=\"$name\">\n";

 

Step 3 - Insert each option.

Add a FOR loop to get each value from the array in this case four different fruits. Use the count() function to find out the total number of values in the array then execute the code below for each value.

for ($x = 0; $x < count($select_array); $x++) {

 

Step 4 - Get the selected value.

Use an IF statement to determine if the current value from the array is the value that should be selected by default.

if ($select_array[$x] == $selected) {

 

Step 5 - Write the <OPTION SELECTED> code.

Just add the new HTML to the previous information contained in $select using " .= " instead of " = " only. Don't forget to close the IF statement with " } "

$select .= "<OPTION SELECTED>$select_array[$x]</OPTION>\n";

}

 

Step 6 - Write the <OPTION> code.

Use an ELSE statement to write the non-selected option code again adding the new HTML to the old with " .= " and not " = ". Don't forget to close the ELSE statement with " } "

else {

$select .= "<OPTION>$select_array[$x]</OPTION>\n";

}

 

Step 7 - Finish up.

Close the FOR loop with " } ", close the Select tag with </SELECT>, Return a value, and close the function with " } ".

}

$select .= "</SELECT><BR>\n";

return $select;

}

 

The final code should look like the following:

function build_select_field()

function build_select_field($name,$select_array,$selected) {    $select = "<SELECT NAME=\"$name\">\n";    for ($x = 0; $x < count($select_array); $x++) {        if ($select_array[$x] == $selected) {            $select .= "<OPTION SELECTED>$select_array[$x]</OPTION>\n";        }        else {            $select .= "<OPTION>$select_array[$x]</OPTION>\n";        }    }    $select .= "</SELECT><BR>\n";    return $select;}

So this would be quite silly to use if you need only one or two select fields unless you place your function in it's own file and include that file's contents in pages that use forms. But if you have several select fields and/or many options in each field, this could save you a lot of time.

With a little more PHP or a modified call, the build_select_field() function can build a select field from any array including databases like MySQL.

 

Hope this helps cut your work load coding forms.

This same technique can be applied to Tables as well but I love the idea for headers and footers. Every page in you website can have the same appearence by simply writing a code for all of the pages HTML code except that which is specific to that page. That way your format would be uniform while the content changes.

 

Happy coding :P

vujsa

Share this post


Link to post
Share on other sites

Now this is what I'd call an excellent article vujsa. The techniques you've shown here are extremely nifty and BIG time-savers when you want to avoid repetitive code. Moreover, one can easily put these techniques together in a library/class and utilize them for rapid dynamic code generation. Plus they clearly demonstrate your vast knowledge on the subject and of course all those years of experience that you've had clearly speaks out for itself.. We'd expect loads of more such great posts from you... Welcome to Xisto and hope you have an enjoyable stay.All the best and cheers :P

Share this post


Link to post
Share on other sites

this tutorial is really good! im trying and starting to learn php for couple of days now and this is the best tutorial yet. maybe the first on php for me. yeh its true that when you coding in html you have to repeat the same bliming tags to make a same effect as the others. hopefully this will help me on my first php based website! so far its only pure html and a bit of css styeling, and thats its. just beginning to broadening my horizon just a little bit more, until i reach my goal of learning c++ which i heard is very hard.thanks again!

Share this post


Link to post
Share on other sites

harriko,

If you are trying to learn PHP and already know HTML, I would suggest writing a PHP script that simply makes a normal static HTML page in order to get used to the program basics and simple string functions.

 

Small Example:

<?// First let's write the HTML - HEAD$html = "<HTML>\n";$html .= "\t<HEAD>\n";$html .= "\t\t<TITLE>\n";$html .= "\t\t\tMy First PHP Project\n";$html .= "\t\t</TITLE>\n";$html .= "\t</HEAD>\n\n";// Next let's write the HTML - BODY// and fill it with content!$html .= "\t<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\" LINK=\"#0000FF\" VLINK=\"#800080\">\n";$html .= "\t\t<H1><CENTER>My First PHP Project</CENTER></H1><BR>\n";$html .= "\t</ BODY>\n";$html .= "</HTML>\n";// Now let's output that HTMLecho $html;?>

This will give you a platform to experiment with.

 

Happy Coding, :P

vujsa

Share this post


Link to post
Share on other sites

great tutorial, very well explained :blink:. I'll probably try and play with it later, Thumbs up!With some good time, I would expect this sort of idea could be used to actually make a simple website generator...hmm.

Edited by uNiT (see edit history)

Share this post


Link to post
Share on other sites

Even though this has been on here a while, I haven't ever come across it.This is a very good idea that I never thought of....yet in many ways it seems to make so much sense...Although isn't this somewhat how a lot of like forum and cms type software work? (Not all but some? Not exactly this concept, but some similar ideas?)One thing about this though is that it isn't exactly easier for the server....i think the php code will take it longer to process, so high volume sites could add load to a server that isn't necessary in all respects, so I am not sure if it is best to use this for all cases?

Share this post


Link to post
Share on other sites

Well nice tutorial - am Example! But when do you need to write HTML code with a PhP chunk? To me it seems much easier to have a text file with the HTML file - call it template - and insert in it only the new elements I need dynamically dependng on a conditional statement.Another way is - if you want to use PhP to write your HTML code is to read the above template file in an array (or even from the database) and insert it at the place where you need it with a simple function.Well thats my view...I used to use C code to create LaTeX graphics in a similar manner and I am preparing to generate the PhP code for my web site like this.Actually if you want to save writing, you have to use loops - looping is the power of the computers!

Share this post


Link to post
Share on other sites

Well, last things first and first things last...The tutorial actually uses a loop to add the options to your select field.Even if you have your loop and a template as you wish, you still need to code the rest of the script to use your variables...This tutorial was meant to should how you could format any variable into any type of output but since PHP is primarily used to output HTML to a web browser, I thought that this example would be easiest for readers to relate to.Looking at the tutorial from a beginners point of view, here are the concepts you learn:Writing Custom FunctionsCalling FunctionsLoopsString OutputUsing count()As far as when do you need to write HTML with a PHP chunk is only when you want people to see the results! Generally speaking, if you see it on your browser and it has a .php extension, then PHP wrote the HTML. Oddly enough, even when I use a template file or files, I usually use several functions in it. Each template bit is it's own function. I then try to make the template file use as little PHP as possible and try to make the PHP file use as little HTML as possible so that when the end user tries to change the way the HTML looks, they don't get overwhelmed with PHP code. But at the end of the day, the PHP file just reads the desired template bit adds the variables and outputs the desired HTML where the function is called.But, I don't want to get too advanced for this beginner topic.vujsa

Share this post


Link to post
Share on other sites
Dont agree.Rapid HTML code generation using simple PHP

Your idea is a maintenance nightmare.  The smallest amount of code is NOT the goal.  The goal is to be able to have a person who has never seen the code be able to modify it without hassle.  Loops to save lines of code are a bad practice. No different than short cryptic variable names: don't do it, be verbose.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.