FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP Tutorials





WickedGravity
Please post all PHP tutorials as replies under this topic.
bluebird
u can visit www.devresources.net or www.php.net for php tutorials

enjoy

thanks
Tiger
There are a lot of free PHP tutorials out there, and even some paid ones. The best one that I have found in my searches is at:

http://www.tizag.com/phpT/

Besides the free PHP tutorial, they also offer:

Beginers Tutorials:
HTML Tutorial
CSS Tutorial
XML Tutorial
SQL Tutorial
PERL Tutorial

Advanced Tutorials:
JavaScript Tutorial
MySQL Tutorial

And if that's not enough, they also have:

First Website Guide
Web Host Guide
HTML Reference
CSS Reference
Live CSS Examples

All-in-all it's a nice, attracctive, easy-to-use site, especially for beginers. I have used this site myself, so I can verify that their tutorials are both useful and free.

Good luck with your studies!
astra
A valuable PHP tutorial for beginners on the site:

http://www.w3schools.com/php/default.asp

From this tutorial you will learn about PHP, and how to execute scripts on your server.

You will see that PHP is a powerful tool for making dynamic and interactive Web pages.


Table of Contents

Introduction to PHP
What PHP is, what a PHP file is, how PHP works, and what PHP can do for you.

PHP Installation
What you need to get PHP up and running!

PHP Syntax
Basic PHP syntax.

PHP Operators
The different operators used in PHP.

PHP Conditional Statements
Explanation of the if...else... statement and the switch statement.

PHP Looping
Explanation of the while statement, the do while statement, and the for statement.

PHP Functions
Some useful PHP functions.

PHP More Functions
Some other useful PHP functions.

PHP Forms
How PHP deals with HTML forms.

PHP Cookies
How to set and retrieve cookies in PHP.

PHP Including Files (SSI)
How to include files in PHP.

PHP Date()
How to work with Date formats in PHP.

PHP ODBC
How to connect to a database.

Enjoy and good share!
nik
here is some php Tutorials:

http://phpbuilder.com/

http://www.phpfreaks.com/

http://www.w3schools.com/php/

note that you shuld know c and html
sonam
You can find one very good PHP tutorial on
http://www.hudzilla.org/phpbook/index.php

There is tons of useful examples.

Other good one is
http://www.spoono.com

Sonam Very Happy
dacode
Hi all,

here are my fav' bookmarks, mainly in french :

http://codewalkers.com/
http://www.phpcs.com/
http://pear.php.net/
http://www.phpclasses.org/
http://phpdebutant.org/
http://www.phpfrance.com/
http://www.phpfreaks.com/
http://www.phpteam.net/
http://www.phpworld.com/
http://phpbuilder.com/
http://www.phpdeveloper.org/
http://php.resourceindex.com/
http://www.01php.com/
http://sourceforge.net/projects/phplib
http://phpinfo.net/
http://dietrich.ganx4.com/nusoap/
http://www.faqts.com/knowledge_base/index.phtml/fid/51/
http://www.php-editors.com/
http://www.phportail.net/
http://www.pscode.com/vb/default.asp?lngWId=8
http://www.koders.com/
http://php.developpez.com/cours/
Guest
here is another nice tut site http://www.hotscripts.com/


grtz
tidytrax
http://www.devarticles.com/c/b/PHP/

Wink
tyxl
You can find scripts right here: http://www.phpfreakz.nl/library.php
the site is in dutch (my language) but the code stays english Smile
it's one of the bigger script databases I know where all code is free ...
supjapscrapper
Tiger wrote:
There are a lot of free PHP tutorials out there, and even some paid ones. The best one that I have found in my searches is at:

http://www.tizag.com/phpT/

Besides the free PHP tutorial, they also offer:

Beginers Tutorials:
HTML Tutorial
CSS Tutorial
XML Tutorial
SQL Tutorial
PERL Tutorial

Advanced Tutorials:
JavaScript Tutorial
MySQL Tutorial

And if that's not enough, they also have:

First Website Guide
Web Host Guide
HTML Reference
CSS Reference
Live CSS Examples

All-in-all it's a nice, attracctive, easy-to-use site, especially for beginers. I have used this site myself, so I can verify that their tutorials are both useful and free.

Good luck with your studies!


Hammer, Krass, lie the germans say!
It's smooth-looking, easy-to-browse, interesting tutorials.
I've never really learned PHP outside from books, and the official website where you can fond documentation about all functions of the language, but for those of you who speak french, it would be great to have a look at this one:
www.developpez.com
it's the most reknowned french-speaking programming portal! Great!
Fasga
http://webmonkey.com/ is an awesome site for all kinds of scripting.
sprogo
Php tutorial pages I visit often:

http://www.phpfreaks.com/
http://www.w3schools.com/

But I recommend the official web site of php: You can find a lot of articles and links there.

http://www.php.net/
rapidfire
I'm using this web site for my tutorials, the give a basic flavour of the language and style.

http://www.freewebmasterhelp.com/tutorials/phpmysql/1

then i use www.php.net for my reference
becks78
Try this, free scripts and codes:
http://www.planet-source-code.com
mattd8752
http://www.frihost.com/forums/vt-18385.html That is a tutorial I just wrote based on bbCode Parsing. It is quite simple, I am working on part 2.
snowboardalliance
I'm learing from http://www.hudzilla.org/phpbook/index.php and it is great. I highly recommend it to anyone learning php for the first time.
clogfan
I'm relatively new to PHP.

I found an interesting page that contains lots of tips and guidelines. Have a look here : http://www.frihost.com/forums/vt-4587.html. This is very good information for everyone starting to develop in php.

And on this site (

http://www.phpbuilder.com/columns/chow20040921.php3?page=1) you find information about how to use Eclipse as your IDE for developing in PHP. I'm using this IDE for my development, and are quite satisfied about it, although it is basic compared to what Eclipse offers for java developers (JDT). I hope this plugin will evolve !!
adam4u
This is a site about programming in general too :
Rolling Eyes http://www.allfreetutorials.com/phptutorials.htm
danikuzi
A good tutorial in Hebrew:
http://www.webmaster.org.il/guide.asp?subject=php
liornetwork
thx for all the links you helpd a llot! Wink Very Happy
lLilian
Lol thanks very much they helped me out a lot!
kenetix
Here's what I found at my bookmarks:
http://www.depiction.net/tutorials/php/
http://www.ibzi.net/
http://www.codedemons.net/tutorials/
Hope somebody will find something interesting on them.
Motif
Thanks guys, that might help me! Smile
vignesh_natraj
To create a forum like this one should we just install php or write some codes into it. pl help
ynad777
Thans for this lot of tutorials about php. They help me many!!!
BCP88
Thanx for so mutch site's, it will help me with my site.
samr_vene
Another good one is http://www.joe2torials.com/ .
Alexduthoit
for the french people, there is www.siteduzero.com
This site is very good! (I learn php on it)
carlokes
OMG...thank you for all the tutorials.
Right now i'm learning how does php work and i find it very interesting...
raki_sg
hi,
No French please... there is a french language post please post
it there..

Alexduthoit wrote:
for the french people, there is www.siteduzero.com
This site is very good! (I learn php on it)
asturmas
http://www.phpfreaks.com/tutorials.php
http://www.thesitewizard.com/php/index.shtml
http://www.w3schools.com/php/default.asp
http://www.tizag.com/phpT/
http://www.phpbuilder.com/
http://www.zend.com/zend/tut/
http://www.developertutorials.com/tutorials/php/
http://www.thescripts.com/serversidescripting/php
http://www.devshed.com/c/b/PHP
airh3ad
i need free invite form php please any one know any site i can download?
landxxx
I like programering in PHP.

Do you have script for mail with attachment (prefer *.gif, *.jpg, ....)
Any script on internet is with small error and very complicated
sinaryuda
If you are lucky enough to be hosted on (or indeed own) a server running GD2.0 or above, you'll have the ability to use truecolour images in jpeg [3] format (and in png [4] if version 2.0.4+) and therefore, you won't really benefit by reading this tutorial. Those using GD2.0+ should be opting to use ImageCreateTrueColor in place of ImageCreate, and ImageCopyResampled in place of ImageCopyResized to assure use of maximum colour levels. If you're running anything under 2.0, read on!
Creating the Image

The function ImageCreate(x_dimension,y_dimension) in GD is restricted to a palette of 256 colours, and as such, it rarely outputs an image at a quality that's acceptable to most Web designers. Fortunately there is a way of getting around this restriction, and maximizing the palette to 16.7 million colours. To enable this, you'll need a graphics editor that's capable of saving jpegs with zero compression, a GD-capable server, and a few spare minutes to read this tutorial.

A quick explanation of the concept...

If you use ImageCreateFromJPEG($image_pointer); your usable palette will exactly mimic that of the image to which you point. So, if we throw away the ImageCreate(width,height) function and focus on trying to use ImageCreateFromJPEG, we should be heading toward a better palette. Those of you who are conversant with GD (or the swifter thinkers among you) might already have noted that creating from a hosted image does not allow us to specify a width and height for the image we've created. If our resource image is 400px by 200px, and we want to create a thumbnail wiht a maximum dimension of 100px, then we'll want a base image of 100px by 50px.

This limits us to two options:

1. Either we upload base images at all the width-height variations needed by our script, and dictate which one to use through a little basic mathematics, or

2. We use one image that's sized to accommodate any dimension we will need, and which will only draw to a designated area of that size, leaving any edges blank/page colour.

If all your displayed images are the same size, you won't have any major problems to solve -- you can simply base your images on a large blank palette that is presized to the dimensions you need. And if you feel like exploring the first option and uploading multiple base images, you should be able to manage with the hints you've already picked up here.

The rest of this tutorial will deal with the second option. We'll look at how to deduce which area of the created image to draw to, and the tips and hints provided here should get you up and running quickly!

Basic Thumbnail Rules

1. Be Kind To Your Server

It's easy to display a group of thumbnails just by iterating through the images in a directory, and pushing them all through a thumbnailing script. Because it is so easy, some people do exactly that at every page load, which quite obviously is a little server- resource hungry. A much better alternative is to save an actual thumbnail image onto the server and simply display that.

2. Protect your Thumbnailing Scripts

For versatility, you'll want a few variables that control output of the thumbnail. You'll need an image pointer at the very least, maybe a switch that allows you to save a copy to the server if need be, and perhaps a compression setting. With those in place, you'll want to assure that no one can enter a URL that will override your usual settings. The typical options of sessions or .htaccess will do fine.
The Scripts

Currently we're trying to create a new image that represents another image whose dimensions are not known prior to running the script.

As we discussed, we'll want to have available a few variables that allow us to specify our resource image, control whether a copy is saved on the server, and control the output compression ratio.

But we can also use a session check to control whether the script is run or not. Perhaps our administration panel could register a session called 'allow_thumbs' to enable the script. We'd call this script using the src attribute of an <img> tag, in a manner similar to this:

<img src="thumb.php?basepath=foldername/
&img_ref=nicebig.jpg [5]&create=yes&compress=65">

Because we will be using exactly the same base image each time, we can also hard code the dimensions into the tag, along with an alt=. You will, no doubt, find your own system for building the calling tag, based on your current administration set up.

Another thing to note about calling through the src of an <img> tag is that any parse errors that occur in the script will not be echoed to the page. All that will happen is that you'll see an image-not-found space on your page. If you need to see the error returns for debugging purposes, you'll need to temporarily remove the session protection, and access the script directly through a URL call.

The following script will produce a thumbnail by using a blank base image, rather than the ImageCreate() function. An explanation of the specific syntaxes follows.

session_start();
if($HTTP_SESSION_VARS["allow_thumbs"] == "yes")
{
header ("Content-type: image/jpeg");

// define the small, square image that will be
// used as the thumbnail base

$palette_image = 'foldername/large_palette_base_image.jpg';

/****** You shouldn't need to edit below here ******/

// Set some defaults values for variables that have not
// been passed to the script through the url

if(!isset($HTTP_GET_VARS['create']))
{$HTTP_GET_VARS['create'] = 'no';}
if(!isset($HTTP_GET_VARS['basepath']))
{$HTTP_GET_VARS['basepath'] = '';}
if(!isset($HTTP_GET_VARS['compress']))
{$HTTP_GET_VARS['compress'] = 100;}

// establish where on the thumbnail we can draw to

$thumbsize = getImageSize($palette_image);
$maxdim = $thumbsize[0];
$draw_from = $HTTP_GET_VARS['basepath'].$HTTP_GET_VARS['img_ref'];
$dim = GetImageSize($draw_from);
if($dim[0]>$dim[1])
{
$to_w = $maxdim;
$to_h = round($dim[1]*($maxdim/$dim[0]));
$to_x = 0;
$to_y = round($maxdim-$to_h)/2;
}
else
{
$to_h = $maxdim;
$to_w = round($dim[0]*($maxdim/$dim[1]));
$to_y = 0;
$to_x = round($maxdim-$to_w)/2;
}

// create some base images to start designing from
// and make initial basic thumbnail

if($dim[2]==1) {$from = ImageCreateFromGIF($draw_from);}
elseif($dim[2]==2) {$from = ImageCreateFromJPEG($draw_from);}
elseif($dim[2]==3) {$from = ImageCreateFromPNG($draw_from);}
$thumb = ImageCreateFromJPEG($palette_image);
// $set_bg_colour = ImageColorAllocate($thumb,255,0,0);
// $fill_bg_colour = ImageFill($thumb,0,0,$set_bg_colour);
ImageCopyResized($thumb, $from, $to_x, $to_y, 0,
0, $to_w, $to_h, $dim[0], $dim[1]);

/******* Image Manipulation Scripting *******/

// extra image manipulation can go here

/***** End Image Manipulation Scripting *****/

// output the created thumnbnail onto the calling page
// and, if $create has been set to 'yes', also create
// a copy of the thumbnail on the server

ImageJPEG($thumb,'',$HTTP_GET_VARS['compress']);
if($HTTP_GET_VARS['create'] == "yes")
{
ImageJPEG($thumb,$HTTP_GET_VARS['basepath'].substr
($HTTP_GET_VARS['img_ref'],0,
strpos($HTTP_GET_VARS['img_ref'],'.')).'_thumb.jpg',
$HTTP_GET_VARS['compress']);
}

// destroy all the temporary images used by the
//server while executing this
scriptlet (tidying up)

ImageDestroy($from);
ImageDestroy($thumb);
}

The script above will take a resource image (referenced by img_ref= in the calling url) and reduce it to a thumbnail that fits centrally within the palette image (the blank image used to extend the palette). The palette indexes on the resultant thumbnail will be increased to a maximum size that mirrors that of the palette image. You might like to copy the above script and refer to it during the following explanations.
Syntax Explanations

Let's now step through the script, and explore what happens at each point.

# Session - is simply there for security. You could do session_start(); $allow_thumbs = "yes"; session_register("allow_thumbs"); in your admin page to activate the thumbnailing.

Alternatively, you could remove the session parts and put the thumbnailing script in a folder with a safeguarding .htaccess file. Either way, just make sure people cannot access the script by typing in the URL.

# header() - to output to a page or file, a header type must be sent. We chose jpeg due to its compression ability.

# $palette_image - the path (absolute from root, or relative to this script) and name of the square blank image that is to be used as a thumbnail base. I emphasized "square" because you must use a square image with the above script. To create a nice truecolour image, simply:

# open your graphics program,

# make a new square (have I mentioned that it should be square?) image,

# increase colour depth to maximum (if it isn't already), and

# save it as a .jpg.

You might also like to fill it with the same colour as the background of your page before you save. Lastly, upload it and change the value of $palette_image to reference this new file.

# default values - to avoid always having to pass every variable=value pair through the URL call, we just set some default values for use if the variable isn't set. For instance, if we called an image with img src="thumb.php?img_ref=blat.png", the script would automatically set to create=no, basepath='' and compress=100.

# establish draw area - using GetImageSize(), we find the height and width of both our resource image, and thumbnail base. We check which is bigger on the resource image (whether it is portrait or landscape) and reduce that to mimic the space available on the thumbnail base. Some reasonably easy mathematics can then be used to deduce the other dimension and the top left pixel of our draw area. We have...

# $to_h - height of the area to draw to

# $to_w - width of the area to draw to

# $to_x - horizontal position of first pixel, counted from the left

# $to_y - vertical position of first pixel, counted from the top

# create some images - for GD to do any image manipulations it needs to create a copy of the designated image and work from that. We need it to create two images, the thumbnail base (which we called $thumb), and a copy of the resource image (which we called $from). Our earlier use of GetImageSize on the resource image also yielded an index that holds the filetype. A quick bit of value testing will reveal that we can create our copy of that image -- be it a .gif [6], .png or .jpg -- which means our script is a bit more versatile now.

# // $set_bg_colour - if you didn't fill your thumbnail base image with the same colour as your page background, you should un-comment this line and the $fill_bg_colour line. You should insert rgb values into the ImageColorAllocate($thumb, red, green, blue) call to mimic your page colour. You could even pass these in as variables in the calling URL.

# ImageCopyResized - using all the mathematically deduced values, we use this function to take the entire area of our resource image, shrink it and copy it to the rigidly defined area of our thumbnail base.

# /* image manipulation scripting */ - if we wanted to perform any further manipulations on our thumbnail, we would do so in this area. Further along in this tutorial are a couple of code snippets that you could plug in here.

# ImageJPEG - this is the call that outputs an image to the browser.

# if (create = "yes") - to save a copy of the thumbnail we've created onto the server, we need to use the middle parameter of the ImageJPEG function. We test if our variable create has explicitly been set to "yes" and, if so, we rip apart the resource image name to remove the extension and create a file based upon [that image name]_thumb.jpg.

Note that you will need the directory that you save your thumbnails into to be chmodded to pretty high permissions. You might also want to put the thumbnails in their own seperate directory, in which case you'll want to amend the path - eg. to $HTTP_GET_VARS['basepath']. 'thumbnail_folder/' .substr($....

# ImageDestroy - because GD had to create images to work from, we end all manipulation scripts by destroying those temporary images from the server.

I've tested this script using GD1.6.2 and GD1.8.4, which both performed admirably -- certainly an improvement on the 256 colours allowed in the use of ImageCreate().

Now we've got the basics, let's take a look at how we can use further image manipulation functions...
Further Manipulations

In the prior script, there was an area commented out as /* image manipulation scripting */, which was empty. If we wanted to try a few weird and wonderful effects on our thumbnails, we could add code here, integrating all the variables we defined or deduced earlier.

An example idea might be to add a shadowed bevel to the thumbnail, perhaps with light colour shading on the top and left, and dark colour shading on the right and base. To give you an idea of the techniques involved, I'll take the shadowed bevel idea and step through it slowly.

Shadowed Bevel

A useful function in GD is ImageCopyMerge, as it allows us to merge a part of one image onto our thumbnail. It is especially useful because we can also define an opacity for the merged portion (which to you and me means shading). If we use a short for loop to count how far we are from each edge of the thumbnail, we can also use that incremental number to work out the opacity with which we'll draw our dark and light lines.

// create a dark image and a light image

$dark_shadey = ImageCreate($maxdim,$maxdim);
$nadir = ImageColorAllocate($dark_shadey,0,0,0);
$light_shadey = ImageCreate($maxdim,$maxdim);
$nadir = ImageColorAllocate($light_shadey,255,255,255);

// decide how wide we want our edge shading

$edge_width = 10;
for($edge_pixel = 0; $edge_pixel < $edge_width; $edge_pixel++)
{

// work out the opacity relative to how far from the edge we are

$opacity = 100 - (($edge_pixel+1) * (100 / $edge_width));

// merge a bit of the light image along the top and left side
// merge a bit of the dark image along the base and right side

ImageCopyMerge($thumb,$light_shadey,$to_x+($edge_pixel-1),
$to_y+($edge_pixel-1),0,0,1,$to_h-(2*$edge_pixel),$opacity);
ImageCopyMerge($thumb,$light_shadey,$to_x+($edge_pixel-1),
$to_y+($edge_pixel-1),0,0,$to_w-(2*$edge_pixel),1,$opacity);
ImageCopyMerge($thumb,$dark_shadey,$to_x+($to_w-($edge_pixel+1)),
$to_y+$edge_pixel,0,0,1,$to_h-(2*$edge_pixel),$opacity-20);
ImageCopyMerge($thumb,$dark_shadey,$to_x+$edge_pixel,$to_y+
($to_h-($edge_pixel+1)),0,0,$to_w-(2*$edge_pixel),1,$opacity-20);
}

// destroy the two new images that we used

ImageDestroy($dark_shadey);
ImageDestroy($light_shadey);

You might notice I've used a few weird syntaxes here, such as reducing the dark image opacity by 20 in the ImageCopyMerge calls. This is simply because the resultant image looks better if the dark isn't quite as dark as the light is light. If you decide to code your own manipulations, you will (more than likely) have to add a few workaround syntaxes like this to your own scripts.

Just to keep you going, here are a couple more manipulations that can be cut and pasted into the /* image manipulation scripting */ area of the main tutorial script.

Spider's Web

This small plugin scriptlets produces a spider's web effect, which is drawn over the thumbnail in the colour defined as $zenith. This script simply draws a few lines from the lower left corner at various angles, and then draws elliptical arcs centred at the same corner.

$zenith = ImageColorAllocate($thumb,255,255,255);
for($draw = 0;$draw<$to_h;$draw+=12)
{
ImageLine($thumb,$to_x,($to_h+$to_y),($to_w+$to_x),
(($to_h-$draw)+$to_y),$zenith);
}
for($draw = 0;$draw<$to_w;$draw+=12)
{
ImageLine($thumb,$to_x,($to_h+$to_y),($draw+$to_x),
$to_y,$zenith);
}
for($draw = 1;$draw<14;$draw++)
{
ImageArc($thumb,$to_x,($to_h+$to_y),$draw*($to_w/4),$draw*
($to_h/4),270,0,$zenith);
}

Doughnut

This larger plugin scriptlet produces an elliptical shaded doughnut thumbnail. The background and shading colour is defined by $zenith. This manipualtion works by iterating through the thumbnail one pixel at a time, and deciding exactly how much opacity to apply when merging a small dot at that place.

$dot = ImageCreate(1,1);
$zenith = ImageColorAllocate($dot,255,255,255);

for($ypos=0;$ypos<$to_h;$ypos++)
{
for($xpos=0;$xpos<$to_w;$xpos++)
{
$xdist = abs(($to_w/2)-$xpos);
if($xdist==0) {$xdist = 0.01;}
$ydist = abs(($to_h/2)-$ypos);
$dist = sqrt(pow($xdist,2)+pow($ydist,2));
$angl = atan($ydist/$xdist);
$el_dist =
sqrt(pow(abs(cos($angl)*$to_w/2),2)+pow(abs(sin($angl)*$to_h/2),2));
if($dist>$el_dist || $dist<$el_dist/6)
{
ImageCopyMerge($thumb,$dot,$xpos+$to_x,$ypos+$to_y,0,0,1,1,100);
}
else {
$dnut_dist = ($el_dist/12)*5;
$offset_dist = abs((($el_dist/12)*7)-$dist);
$uppy = sin(acos($offset_dist/$dnut_dist))*$dnut_dist;
$opac = 100-((100/$dnut_dist)*$uppy);
ImageCopyMerge($thumb,$dot,$xpos+$to_x,$ypos+$to_y,0,0,1,1,$opac);
}
}
}
ImageDestroy($dot);

I hope that tutorial and the extra little scriptlets have taught you how versatile the GD libraries can be. Perhaps you have even caught the image-manipualtion bug and are eager to start coding your own transformations! Good luck.
sinaryuda
To the new PHP programmer, XML is quite the mysterious thing. Recently I began writing a website that uses an XML template system, so I needed to find an easy way to parse my XML, and output it the way I needed it to be outputted. With PHP4 you have to build your own XML parser that will read and output your XML. So, with that idea I decided begin to explore PHP5, because of its simpleXML extensions.

Before jumping ahead and just building my parser, I knew that I’d have to replace elements in the XML document with data from my database; after all what would be the point of using XML for a template system if you couldn’t replace elements with your own data. So, keeping that in mind I know that I’d have to load each element of my XML document into a variable then send it through my own function to replace the things I need to replace, with the correct information. Now, let’s get started.

The first thing we should look at is the XML document. This is a simpler version of mine, but it’s still the same basic idea. Save the following as template.xml.

<?xml version="1.0" encoding="UTF-8" ?>
<template>
<header>
<![CDATA[
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title><!title></title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align:center;"><!logo></td>
</tr>
</table>
]]>
</header>
<body>
<![CDATA[
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width=”15%”><!column1></td>
<td width=”70%”><!column2></td>
<td width=”15%”><!column3></td>
</tr>
</table>
]]>
</body>
<footer>
<![CDATA[
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align:center;"><!footer></td>
</tr>
</table>
</body></html>
]]>
</footer>
</template>

Let’s play tag:

As you can see the XML document contains three main elements, header, body, and footer. With in each of those we have the basic three column page layout, and a few proprietary tags such as <!title> and <!logo>. These are going to be the elements that we’re going to replace with our own non-template data. So first things first, we need to figure out how to replace the tags with our data. I created the following function to do so.

function replace($load,$string,$mask='<!-tag->'){
if(!is_array($load)){
return $string;
}else{
if(!strpos($load,'-tag-')) $mask='<!-tag->';
$masks=explode('-tag-',$mask);
$tags=array_keys($load);
foreach($tags as $tag){
$newtags[]=$masks[0].$tag.$masks[1];
}
$loads=array_values($load);
return str_replace($newtags,$loads,$string);
}
}

Before we go any farther, lets take a look at this function so you know exactly what it does.

First we define the function and all the parameters it will accept:

* $load is the array of tags we’re going to replace, the array should be set up like this array(‘tagname’=>”data to place where the tag is”)
* $string is the variable that holds the XML string that we’ll later get from simpleXML
* $mask is an optional variable that you can use incase you want to use a different tag style, such as <*tag> function replace($load,$string,$mask='<!-tag->'){

Then we make sure that $load is an array so that we don’t get any nasty unexpected errors. If it’s not an array the function will just return the XML string without processing it

if(!is_array($load)){
return $string;
}

If $load is an array, we first make sure that there isn’t a tag in the $load named “-tag-“(1). Then we explode the $mask tag by “-tag-“ so that we have an array that has the opening and closing brackets for each tag, “<!” and “>”(2). Now you might say “why all this stuff about the tags being explode to simply get the ‘<!’ and ’>’.” The reason behind that is so that you can change the tag style to something else like <*-tag-> if you want.

(1) if(!strpos($load,'-tag-')) $mask='<!-tag->';
(2) $masks=explode('-tag-',$mask);

Now we’re about to use a built-in PHP function that isn’t used too often but is very useful, array_keys(). array_keys() returns the keys of the input array as the values of the output array consider the following.

$array1 = array('key1'=>"value1",'key2'=>"value2");
$array2 = array_keys($array1);
print_r($array2);

This will output:

Array
(
[0] => key1
[1] => key2
)

Pretty cool and useful isn’t it.

Now we’ll use array_keys() to get all the names of the tags from the $load array we load that into $tags (3). Then we run the $tags array through a loop to get the value of each of the array keys (4). Now we build our new list of the actual tags to replace (this is a little easier than searching the XML document to find all the replaceable tags) (5). Now we use another built in function that’s just like array_keys() but instead of operating on the keys it operates on the values. It’s surprisingly named array_values() (6). Then we put it all together and run it through srt_replace() which with loop through the arrays that we pass to it (7). Str_replace() will return a string will all occurrences of $newtags in $string replaces with $loads respectively.

(3) $tags=array_keys($load);
(4) foreach($tags as $tag){
(5) $newtags[]=$masks[0].$tag.$masks[1];
}
(6) $loads=array_values($load);
(7) return str_replace($newtags,$loads,$string);

That’s about it for the replace() function. Now let's move on to how we plan on getting the XML elements to the replace() function.

Give it a little class:

Now, for the part that you probably started reading this article for, simpleXML. SimpleXML works a lot like your average PHP class. You simply set simplexml_load_file() to the value of a variable and call a file name with it to load the XML document into the script then you use the -> operator to call each element of the XML file, such as in the following snippet that uses our template.xml.

<?
//load the template.xml file.
$template = simpleXML_load_file(template.xml);
//load the header element as a string
$header = $template->header;
//output the header element
echo $header;
?>

Go ahead and try that, then check the page source in your browser and you’ll see the exact html that’s in the header element of the template.xml file. Compare that to doing the same thing in PHP4 and you’ll understand why it’s called simpleXML. As you can see simplexml_load_file() basically loads the XML file into the $template variable and sets it up as if it’s a class and you call each element as if it were a class’s variable. Pretty simple isn’t it, hence the name simpleXML. Now that you know how simpleXML is going to help us load the xml file, we’re going to talk about how to build it all to easily load your XML template file into your script, then replace the tags, without have a bunch of the $template-> lines.

First off you know how your own XML template file is built, so knowing what elements and tags it had won’t be a problem. Secondly it’s faster at parse time to parse a function that will loop through an array of all the elements than it is to parse multiple lines that call each of the elements alone. So what we do is make a function that will accept an array that will hold the names of all the elements, then run them through the replace() function, then output them. I actually created a class to handle the loading of the XML file, building the elements array, building the tags array, and outputting it all. Here’s what I have.

<?
class template
{
public $xml_path; //holds the path to our template files
public $xml_file; //holds the filename of the XML file
public $elements; //holds the array of all our XML elements
public $element; //temporary storage of an individual XML element
public $load; //holds the array of all our tags
public $tmpl_file; //holds the combined path and filename of our template file
public $tmpf; //holds the XML file after being loaded by simpleXML

function load(){
if(isset($this->xml_path)&&isset($this->xml_file)){ //make sure that both variables are set
$this->tmpl_file=$this->xml_path.$this->xml_file; //combine the XML path and filename to make one string
}else{
$this->tmpl_file="fail/safe/path/to/your/xml_file.xml"; //if both variables aren’t set load a failsafe XML file
}
if(file_exists($this->tmpl_file)){ //make sure the set XML file exists
$this->tmpf=simplexml_load_file($this->tmpl_file); //load the XML file into the variable $tmpf
}else{
return "Error Loading Template Data: File Not Found"; //send an error if the XML file can’t be loaded
}
}

function parse_elem(){
if(is_array($this->elements)){ //make sure that the elements variable is an array
foreach ($this->elements as $elem){ //loop through each element
$this->element=$this->tmpf->$elem; //set current element as the value of $element
if($this->element!=""){ //check to make sure the element isn’t empty
$page.=$this->replace($this->load,$this->element); //add the output of the replace function to our output variable
}else{
$page.="Error Loading Template Data: Element \"$elem\" Not Valid<br />"; //add an error incase the element is invalid
}
}
}else{
return "Error Loading Template Data: Element Data Not Valid<br />";//send an error if the elements variable isn’t an array
}
return $page; //output the final product of our hard work
}

function add_elem($key,$value){//add an element to the elements array
if(isset($key)&&isset($value)){//make sure all information is specified
$this->elements[$key]=$value;//add a key to the elements array containing specified data
}else{
echo "Error Adding Element: Element Data Missing";//send an error incase the correct information isn’t specified
}
}

function add_tags($key,$value){//add a tag to the load array
if(isset($key)&&isset($value)){//make sure all information is specified
$this->load[$key]=$value; //add a key to the load array containing specified data
}else{
//echo "Error Adding Tag: Tag Data Missing"; //send an error incase the correct information isn’t specified
}
}

function replace($load,$string,$mask='<!-tag->'){
if(!is_array($load)){ //make sure load variable is an array
return $string;// if load variable isn’t an array return the string unprocessed
}else{
if(!strpos($load,'-tag-')) $mask='<!-tag->';//make sure the tag mask isn’t in the load array
$masks=explode('-tag-',$mask);//explode the mask array to reveal tag beginning and end
$tags=array_keys($load);//load the keys from load array into another array called $tags
foreach($tags as $tag){ //loop through tags array
$newtags[]=$masks[0].$tag.$masks[1];//build array of the tags for the specified data
}
$loads=array_values($load);//load values from load array into a separate array named $loads
return str_replace($newtags,$loads,$string);//process all tags, replace data and the specified XML string through str_replace()
}
}
}
?>

It’s not actually all that complicated if you just take a second to look at it. Now, to put this all into use. Save the class that I just showed you as parser.php.

That’s a wrap, err, a parse and an echo, then a wrap:

Now we need to use all this for something worthwhile. First we’ll need to set up our elements array for the parser. for this we’ll use the add_elem() function we just made in our class.

$template = new template();
$template->add_elem("header","header");
$template->add_elem("body","body");
$template->add_elem("footer","footer");

as you can see all you do is call the function an pass the names of each element to it, that will build an array in out class called $elements. Personally I just use the name of the element as the array key; it’s just less confusing for me if I need to debug anything in my site. Now we need to build the array of all the tags that we put in our XML document. We’ll use our add_tags() function for that. It works like the add_elem() does, only with a slight difference.

$template->add_tags("title","This is the simpleXML test page");
$template->add_tags("logo","simpleXML is simple!");
$template->add_tags("column1","This is column one");
$template->add_tags("column2","This is column two");
$template->add_tags("column3","This is column three");
$template->add_tags("footer","this is the footer information");

As you can see here, you name the key the same thing that the tag is going to be named, while the value of the key is the information you want to the tag to be replaced by. The value can contain anything it can be a function that has been loaded into a variable ( $var=function()), it can be a number, text, html, more php, anything, as long as it can be outputted to a browser.

After we’ve built our arrays of elements and tags, we’ll have to set our file path and filename that’s pretty easy and painless as well.

$template->xml_path = "path/to/xmlfile/";
$template->xml_file="template.xml";

If the XML file is in the same directory as the index page, then you’ll still need to set the xml_path due to the error checking, but you can set is to a blank.

$template->xml_path="";

That’s almost all that’s left to do now all we have to do is call our function to load the XML file and the function that will output it all to the browser and that’s about it!

$template->load();
echo $template->parse_elem();

That’s it, pretty painless. As you can see the entire contents of all 3 files is less than the contents of most PHP4 version XML parsers, and this has a lot more functionality. This script can be expanded to do a lot more than it does here, in fact I encourage you to expand the script to do amazing things. I know that this script can be expanded to do a lot more than it does as it’s presented in this article because I use the exact same script expanded to do many more things. For example I set up the 3 columns as separate XML elements so that I can add flexibility to my layouts. I haven’t covered all the things you can do with simpleXML in this article, so I also encourage you to check out the rest of the functions that simpleXML offers and play around with them. Who knows what cool things you can actually do with it, because as every PHP developer knows, you can do anything you can imagine with PHP.
Jaime
THere is most useful if you put all this in a homepage and put here the link, thanks....
Astrolopitecos
for those who really need good tutorials of php, css, html, and much more go to Sampson Resume
samay
The first site from which I learned PHP is www.htmlite.com. This is a nice site to start with.
icedrakon
www.freewebs.com/icedrakon

Try my site for 2 great books in php
I have many more but not in a list ask and i will find them...
kuhdorf
yea now I can PHP too^^
cornflake
thanks that helped
ParsaAkbari
I learned PHP all through the internet lol Smile
MovieDesign
cool tutorials at www.tutoriale.ro
xyilarc
Thank you for this tutorial guys!
This really helped me!
Abhishukla
thank you for the information.
welshsteve
samr_vene wrote:
Another good one is http://www.joe2torials.com/ .


I know this guy from the HTML Forums (www.htmlforums.com), he really knows his stuff.
Related topics
Php+Tutorials
PHP Tutorials
PHP tutorials
Php - Basic Encryption site
Simple login system
PHP tutorials
A directory of PHP tutorials, applications, scripts!!!
Learning PHP
Java
Hey everybody ;) HTML or Blog?
how to use php?
Where can I find tutorials for MySQL?
Photoshop, php tutorials
PHP Navigation
Reply to topic    Frihost Forum Index -> Miscellaneous -> Tutorials

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.