Welcome Guest ( Log In | Register )



 
Reply to this topicStart new topic
> Rapid HTML code generation using simple PHP, avoid those repetative boring tasks....
Rating 5 V
vujsa
post Feb 20 2005, 09:22 PM
Post #1


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714



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:
CODE
<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:
CODE
<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:
CODE
<?
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:
CODE
<? 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:
CODE
<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()
CODE
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 cool.gif
vujsa
Go to the top of the page
 
+Quote Post
miCRoSCoPiC^eaRt...
post Feb 20 2005, 09:39 PM
Post #2


PsYcheDeLiC dR3aMeR
Group Icon

Group: Admin
Posts: 2,242
Joined: 29-January 05
From: Nakorn Chaisri, Thailand
Member No.: 2,411



    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 AstaHost and hope you have an enjoyable stay.

All the best and cheers smile.gif
Go to the top of the page
 
+Quote Post
harriko
post Feb 21 2005, 10:29 PM
Post #3


Premium Member
Group Icon

Group: Members
Posts: 279
Joined: 2-February 05
From: UK
Member No.: 2,480



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!
Go to the top of the page
 
+Quote Post
vujsa
post Feb 22 2005, 02:54 AM
Post #4


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714



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:
CODE
<?

// 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 HTML

echo $html;
?>


This will give you a platform to experiment with.

Happy Coding, cool.gif
vujsa
Go to the top of the page
 
+Quote Post
uNiT
post Sep 10 2007, 08:44 PM
Post #5


Newbie [ Level 2 ]
Group Icon

Group: Members
Posts: 20
Joined: 30-July 07
From: California
Member No.: 23,692



great tutorial, very well explained biggrin.gif. 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.

This post has been edited by uNiT: Sep 10 2007, 10:51 PM
Go to the top of the page
 
+Quote Post
.:Brian:.
post Sep 11 2007, 09:14 PM
Post #6


Premium Member
Group Icon

Group: Members
Posts: 219
Joined: 13-February 07
Member No.: 20,371



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?
Go to the top of the page
 
+Quote Post
rockarolla
post Feb 5 2008, 03:47 PM
Post #7


Member [ Level 1 ]
Group Icon

Group: Members
Posts: 48
Joined: 5-February 08
From: Japan
Member No.: 28,155



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!

Go to the top of the page
 
+Quote Post
vujsa
post Feb 6 2008, 07:55 PM
Post #8


Absolute Newbie
Group Icon

Group: Admin
Posts: 888
Joined: 20-February 05
From: Indianapolis, Indiana, USA (Midwest)
Member No.: 2,714



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 Functions
Calling Functions
Loops
String Output
Using 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
Go to the top of the page
 
+Quote Post
FirefoxRocks
post Mar 25 2008, 01:17 AM
Post #9


Super Member
Group Icon

Group: [HOSTED]
Posts: 695
Joined: 12-July 06
From: Ontario, Canada
Member No.: 14,464



I did the exact same thing with an XML file and an XSLT stylesheet. Needed a lot of <option> things.
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. Converting HTML over to XHTML(13)
  2. Code To Send An Email From A Form(10)
  3. Do You Program/code Your Own Games(11)
  4. Alt Txt Tooltip Popups Over Text Links, How To Do?(11)
  5. Uploading Image File Through JSP Code To Server(9)
  6. PHP Tutorial: Form Verification And Simple Validation(12)
  7. Free Code Snippets And Css Layout(14)
  8. Converting PSD To HTML(9)
  9. Did I Install A C Or A C++ Compiler ?(6)
  10. Photoshop Is Sooo Last Generation ;)(2)
  11. A Simple Register Script(3)
  12. Increase Your Knowledge Of Html Language(11)
  13. Simple Java Question(3)
  14. Php Random Selector(2)
  15. How To: Display A Members/user List.(3)
  1. Web Editor(0)
  2. Activation Code(7)
  3. Instant Replay Code?(0)
  4. Indentation In Html(4)
  5. Joomla Template Kit Extension For Nvu/composer(3)
  6. What You Need Before You Can Create A Text-based Game..(7)
  7. Enter Your Password To Perform Administrative Tasks(3)
  8. Basic Html Tutorial(1)
  9. How To Make Simple Animations In The Gimp(2)
  10. How To Understand A Database Schema(4)
  11. Good Books For Html And Css Beginners(1)
  12. Second Generation Microsoft, Google, And Pick The Cat Captchas Broken(2)
  13. [fl]snow Effect(3)


 



- Lo-Fi Version Time is now: 8th October 2008 - 05:02 AM