Wednesday, 16 Jan 2008 6:28PM EST
For those of you out there who are still new to
PHP, I'd like to discuss one of the languages most useful and most powerful features; its integration with
MySQL. PHP and MySQL are integrated so seamlessly that almost anyone can create a dynamic web application based on the pair.
Let's jump right into it. For this tutorial, I'm going to assume that your server is already set up with PHP4+ and MySQL 4.1+.
LAMPHowTo.com has a great tutorial to help you set your server up if you've decided to host your own site. OK, so now that you're all set up, the first thing you'll need to do in your PHP code is connect to the database. For this step you'll need to know the path to your database server, your database username and your password. Plug that information into following code and you'll be ready to start working with your new database.
$host = '/tmp/mysql';
$username = 'mysql_user';
$password = 'mysql_password';
$connection = mysql_connect($host, $username, $password);
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
Next, you'll need to start create tables to store your data in. Creating a table with PHP works like any other MySQL query. You simply store your "CREATE TABLE" statement as a string and pass it to the database with
mysql_query. In this example, I'm going to create a new table to store information about a sites registered users. The fields I'm going to user are
id,
username,
password,
email,
birthday and
hometown.
id will be the primary key for the table and will be an automatically incrementing value. We won't allow any of our values to be NULL.
$query = 'CREATE TABLE users( '.
'id INT NOT NULL AUTO_INCREMENT, '.
'username VARCHAR(20) NOT NULL, '.
'password VARCHAR(64) NOT NULL, '.
'email VARCHAR(50) NOT NULL, '.
'birthday VARCHAR(10) NOT NULL, '.
'hometown VARCHAR(20) NOT NULL, '.
'PRIMARY KEY(id))';
mysql_query($query) or die('Error, create table query failed');
Now that we've got a table, let's fill it with some data. Assume that you've got a form that takes the 5 values (not including id, which will automatically increment from 0) and passes them to a PHP script. Your script grabs the data via the
method of your choice and stores the values in the variables
$username,
$password,
$email,
$bday and
$town.
$query = "INSERT INTO users(username,password,email,
birthday,hometown) VALUES ('$username','$password',
'$email','$bday','$town')";
mysql_query($query) or die('Error, insert query failed');
Now we want to use the data that has been inserted to the
users database. Just write your SELECT statement, pass it to the databse through mysql_query and store the result in a variable. The resulting data will be an 2D array with each column representing one of the values that your database stores (username, birthday, etc.) and each row representing a user. You can use a simple
for or
while loop to cycle through the data.
// Replace column headings with * to SELECT all values.
$query = "SELECT username,email,birthday,hometown FROM users";
$result = mysql_query($result);
// mysql_num_rows($result) returns the number of rows
// in the query result set, i.e. how many users are in
// your database.
for($i=0; $i<mysql_num_rows($result); $i++) {
$username = mysql_result($result,$i,'username');
$email = mysql_result($result,$i,'email');
$bday = mysql_result($result,$i,'birthday');
$town = mysql_result($result,$i,'hometown');
echo "$username, $email, $bday, $town";
}
This code will produce a result similar to:
jspegele, justin@spegele.com, 09/20/1984, Yaphank
johnsmith, john@smith.com, 07/04/1976, New York
.
.
.
So now that you're working with your data, you may want to add in the ability to update and/or delete information. Here's the PHP and MySQL code to accomplish both of those tasks:
// UPDATE
$username = "myuser"; // User to update
$newEmail = "mynewemail@email.com";
$query = "UPDATE users SET email='$newEmail' WHERE username='$username'";
mysql_query($query);
// DELETE
$username // User to delete
$query = "DELETE FROM users WHERE username='$username'";
Finally, close out your database connection:
mysql_close($connection);
And there have it; a quick and easy introduction to using a MySQL database in PHP. As always, if you have a technique or a tweak that you think improves on this code, please share it in the comments. Also, if you have a tip, a trick or an idea for my next post, please don't hesitate to
contact me.
Friday, 11 Jan 2008 7:40AM EST
Today I'm going to delve a bit deeper into PHP classes and talk about
abstract classes. An abstract class is a core class which provides default behavior for and is extended by sub classes. It is important to note that an abstract class is very different from an interface. An interface defines how you work with a class, but does not define how the class itself works. With an abstract class you define the default behaviors of the class as well as what other functions the class needs to perform. Those other functions are simply declared in the abstract class, but are then defined in a class extension.
Let's take a look at a very simple example where we have an abstract class called
shape which defines two variables,
base and
height, a function to set those values and the declaration of a
draw function.
<?php
abstract class shape {
// An abstract classes member that need to be
// accessed by an extension should be declared
// as protected.
protected $base;
protected $height;
// getValue setValue takes a base and height and
// stores them in the protected variables
public function getValue($base,$height) {
public function setValue($base,$height) {
$this->base = $base;
$this->height = $height;
}
// Declare abstract functions, but don't define
// what they should do.
abstract public function draw();
}
?>
Here we are saying that all of our shapes will have
base and
height values, as well as a
getValue setValue function to store those values and a
draw function. The
base and
height values and the
getValue setValue function will be defined in the abstract class, at the core of the shape definition. The functionality of
draw(), on the other hand, will be defined in the sub classes; being that each different shape will need to be drawn in a different way. Here's what your sub classes should look like:
<?php
class rectangle extends shape {
public function draw() {
// Code to draw a rectangle
}
}
class triangle extends shape {
public function draw() {
// Code to draw a triangle
}
}
?>
Here we've defined two shapes, a rectangle and a triangle. Both of these shapes require a base and a height, but are clearly not drawn in the same way, therefore the draw functions are defined separately. To create a new shape, simply define an instance of
triangle or
rectangle and call the
getValue setValue function for that new instance. Since
rectangle and
triangle are extensions of
shape and
getValue setValue is a public function, you will be able to call the function on your new instance.
<?php
$r = new rectangle(); // New rectangle
$r->getValue(25,15); // Send the base and height values
$r->setValue(25,15); // Send the base and height values
$r->draw(); // Draws the rectangle
$t = new triangle(15,10); // New triangle
$t->getValue(25,15); // Send the base and height values
$t->setValue(25,15); // Send the base and height values
$t->draw(); // Draws the triangle
?>
And there's your first PHP abstract class. As I mentioned earlier, the main benefit here is that you can define core functionality for your code that won't need to be copied and pasted into several other classes, while maintaining the versatility of having separate classes that fit your needs. As always, if you have a technique or a tweak that you think improves on this code, please share it in the comments. Also, if you have a tip, a trick or an idea for my next post, please don't hesitate to
contact me.
Wednesday, 09 Jan 2008 8:43PM EST
Here's a nice bit of CSS that will enlarge an image when that it is hovered over. What you need to do is create a link that contains two separate image tags and enclose that within a div that you can specify the height and width of. You can either a small image and a large image, or simply use a single large image and specify a smaller size in one of the image tags. The image tag that you specify
class="full" on is your large image that will display when the thumbnail is hovered over. Here's what the HTML to achieve this should look like:
<div class="expandable">
<a href="#">
<img src="davidandgary.jpg" class="full" border="0"/>
<img src="davidandgary.jpg" class="thumb" width="150" border="0"/>
</a>
</div>
The CSS for this is fairly simple as well. First you need to style the div that will hold the images. Note that for this to work properly in Firefox, the containing element needs to have a specified width. This width should be the width of your larger image. Next you set the
display property of the full sized image to
none and the
position of the hovered link to
relative. Then you have to set the
display of the full sized image when hoverd over to
block, the
position to
absolute, which allows your image to expand over any other elements in your page, and
top to -185px (for this specific image size) in order for this work in standards compliant browsers. That value is not necessary in IE6, though, hence the HTML hack at the bottom of the CSS to reset
top to 0px. The
.thumb class is also an IE6 hack, this one to set the visibility of the small image to
hidden when the large image is displayed.
<style>
/* Class for the div which will hold the images */
.expandable {
/* You must specify a width for the area that contains
the images or Firefox, Opera, and Safari will expand
the hoverable area to the full width available. */
width: 268px;
margin: 0;
padding: 0;
}
/* Hide the full sized image */
.expandable a .full{
display: none;
}
/* Specify the position of the full sized image (for IE) */
.expandable a:hover{
position: relative;
}
/* Display the full sized image when link is hovered over */
.expandable a:hover .full{
position:absolute;
top:-185px;
display: block;
z-index: 1;
}
/* Hide the thumbnail when the full sized image is shown */
.expandable a:hover .thumb {
visibility: hidden;
}
</style>
<!--[if IE 6]>
<style>.expandable a:hover .full{ top:0; }</style>
<![endif]-->
And that does it for a nice bit of CSS to enlarge an image when hovered over. If you have a better technique or a tweak that you think improves on this code, please share it in the comments. Also, if you have a tip, a trick or an idea for my next post, please don't hesitate to
contact me.
View a Live Demo »
Tuesday, 08 Jan 2008 7:13PM EST
Here's a simple yet very useful little JavaScript function I wrote recently which limits the
number of characters a user can put into a standard
<textarea> while
displaying a running count of the number of characters left. The function takes 3 inputs;
the ID of an element which contains the current count (in this case, a
<span>), the ID of the input element, and the desired character limit. The
function is called on the key up of every keystroke for that input. It then counts the
length of the input, checks if more characters are allowed and pushes the number of
characters remaining out the the count element. The function will trim the last character
off of the input string if no more characters are allowed.
The first thing you'll
need to do is create the element to hold the count and the input element. The input element
will utilize
onkeyup
to call
charactersLeft().
<span id="count">25</span> Characters Left<br/>
<textarea cols="50" rows="5" id="myTextArea"
onkeyup="javascript:charactersLeft('count','myTextArea',25);"></textarea>
The next step is to create the
charactersLeft function:
function charactersLeft(count,input,limit) {
// Get the element where the current count is displayed
var countEl = document.getElementById(count);
// Get the element where the text is being entered
var inputEl = document.getElementById(input);
// Get the text from the input element
var inputStr = inputEl.value;
// # of characters left = max input - current string length
var charsLeft = limit - inputStr.length;
// Change text color to red if 5 or less characters are left
if(charsLeft <= 5) {
countEl.style.color = "red";
}
else {
countEl.style.color = "black";
}
// When 0 characters are left...
if(charsLeft <= 0) {
// always set charsLeft to 0 so no negative #'s display
charsLeft = 0;
// trim the extra input off of the input string and push
// to the input element
inputEl.value = inputStr.substring(0,limit);
}
// push the current count to the count element
countEl.innerHTML = charsLeft;
}
And there you have it, a quick and easy way to limit the input allowed in a
<:textarea> and display the number of characters left. Have fun and don't
forget to play with the code. If you have a better technique or a tweak that you think
improves on this code, please share it in the comments. Also, if you have a tip, a trick or
an idea for my next post, please don't hesitate to
contact
me.
View a Live Demo »
Monday, 07 Jan 2008 8:09AM EST
Today I've got a quick and easy way to fade any element in and out using
JavaScript. This is great way to add a little something extra to your site, especially if it is combined with a slide or some other method of
hiding an element. It is important to note that is fade script does not truly "hide" an element from the page, rather it simply makes the element invisible to the user.
Let's jump right in. The first thing we need to do is write our
changeOpacity() function. This function is what will actually change the opacity of the element. This will not achieve the fade, however, because it will only change the opacity of the element from one value to another. It could also be used for any one off opacity changes you need to make. The function takes just 2 variables as input;
el and
opacity.
el is the name of the element you want to change the opacity of and
opacity the the new opacity that you want.
/* changeOpacity() uses three different opacity settings to
achieve a cross-browser opacity changing function. This
function can also be used to directly change the opacity
of an element. */
function changeOpacity(el,opacity) {
var image = document.getElementById(el);
// For Mozilla
image.style.MozOpacity = (opacity / 100);
// For IE
image.style.filter = "alpha(opacity=" + opacity + ")";
// For others
image.style.opacity = (opacity / 100);
}
The next piece of code is the real meat and potatoes of this script.
fade() will do just that for us; it will fade the element by iteratively calling
changeOpacity() as many times as needed to achieve a smooth fade. The function takes 4 values as input.
el is the name of the element that is to be faded,
milli is the number of milliseconds that the fade will take to complete,
start is the starting opacity and
end is the ending opacity.
function fade(el,milli,start,end) {
var fadeTime = Math.round(milli/100);
var i = 0; // Fade Timer
// Fade in
if(start < end) {
for(j = start; j <= end; j++) {
// define the expression to be called in setTimeout()
var expr = "changeOpacity('" + el + "'," + j + ")";
var timeout = i * fadeTime;
// setTimeout will call 'expr' after 'timeout' milliseconds
setTimeout(expr,timeout);
i++;
}
}
// Fade out
else if(start > end) {
for(j = start; j >= end; j--) {
var expr = "changeOpacity('" + el + "'," + j + ")";
var timeout = i * fadeTime;
setTimeout(expr,timeout);
i++;
}
}
}
The third and final function you'll need to complete the fade is
toggle(). Toggle is really only necessary if you want to have a single function call that can both fade the element in and fade it out. If you'd rather, you could just have two separate function calls that call
fade() directly. Here's what your toggle function would look like:
/* toggle() checks to see if the images has already been faded
or not and sends the appropriate variables to opacity(); */
function toggle(el,milli) {
// Get the opacity style parameter from the image
var currOpacity = document.getElementById(el).style.opacity;
if(currOpacity != 0) { // if not faded
fade(el, milli, 100, 0);
} else { // else the images is already faded
fade(el, milli, 0, 100);
}
}
And there you have it, a quick and easy piece of JavaScript code to fade an element in and out. Have fun and don't forget to play with the code. If you have a better technique or a tweak that you think improves on this code, please share it in the comments. Also, if you have a tip, a trick or an idea for my next post, please don't hesitate to
contact me.
View a Live Demo »
Fri, 4 Jan 2008 6:14PM EST
The term
Sprite originates from the early computer graphics technique of using many small images to build a single larger image. This technique became unnecessary as computers grew ever more powerful, though, so the term came to refer to just the single larger image. The term was a natural fit when web designers began combining their icons, thumbnails and other images into a single larger image. And hey, it rolls off the tongue a lot easier than Single Image Multi Replacement. So why are designers combining all of their smaller images into one larger image? To save on bandwith, loading times and server requests. In the early days of the web design, splicing your images gave the appearance of faster load times since individual splices load separately. In reality, a spliced image takes longer to load. The sum is actually less than the whole of its parts. A single sprite will be significantly smaller (in file size) than the sum of all of the individual images that it's made up of.
So now that we know what sprites are and why we should use them, let's figure out
how to use them. The first step is to create the sprite. This is pretty straight forward; just open up your favorite image editor and combine all of your icons or thumbnails into one graphic. You can line them up however you like, just keep in mind that the more organized they are, the easier your job will be. Putting them all one on top of another or all side by side is the easiest way to do this. In my example, I've created two rows of icons; the standard icons on top and the hovered icons on the bottom.

The next step is to style the unordered list (
<ul>) which will contain the icons. You don't have to put them in a list container, though. You could just keep them each in a separate span, paragraph, div, etc. But be careful if you don't use a list. You'll have to make some major edits to how and where the background image is defined. Here's how I styled my list:
* {
/* Reset all margins and paddings to 0 */
margin:0;
padding:0;
}
.share li{
float:left; /* Allows list to display horizontally */
display:inline; /* Fixes the IE double margin bug */
margin:20px 0px 0px 20px; /* Margins around each list item */
}
.share li a{
/* Links must be set to display as a block so that
height and width can be defined */
display:block;
width:50px; /* Height and width of each link block */
height:50px;
/* Define your sprite here */
background:url(sprite_icons.png) top left no-repeat;
}
Now let's go ahead and define the background positions for each of our list items (
<li>). Each list item should have its own unique id so that it can have its own background position defined. As you'll see, I'm using
newPage,
cutTool,
pasteTool and
pageSecurity in order to correspond with my icons. The first value in each property is the horizontal postion and the second value is the vertical position; "0 0" will display the top left icon in the image and negative numbers move you down and right across the image. Note that each of my icons is 50px by 50px. Therefore, in order to display the second row of icons from my sprite, our first value should be
–50px. In order to display the second column, our second value should be
–50px.
#newPage a{ background-position: 0px 0px; }
#newPage a:hover{ background-position: 0px -50px; }
#cutTool a{ background-position: -50px 0px; }
#cutTool a:hover{ background-position:-50px -50px; }
#pasteTool a{ background-position: -100px 0px; }
#pasteTool a:hover{ background-position: -100px -50px; }
#pageSecurity a{ background-position: -150px 0px; }
#pageSecurity a:hover{ background-position:-150px -50px; }
And finally, our last step is to create the list in the body of our page. Simply define an unordered list with a class of "
share" and a list item for each icon, with ids corresponding your those defined in your CSS.
<ul class="share">
<li id="cutTool"><a href="#"></a></li>
<li id="pageSecurity"><a href="#"></a></li>
<li id="pasteTool"><a href="#"></a></li>
<li id="newPage"><a href="#"></a></li>
</ul>
View a Live Demo »
That's it! Have fun and don't forget to play with the code. If you add a little left padding to the "li a" style, you'll be able to add text to your links without it displaying on top of the image. If you have a better technique or tweak that you think improves on the code, please share it in the comments. Also, if you have an idea for my next tutorial, feel free to
send it to me.
Thu, 3 Jan 2008 7:35:00 EST
OK, so everyone knows
PHP lately. It's the simplest scripting language to learn and yet still an extremely powerful one. PHP is the language that many web developers start off with because of that simplicity. Unfortunately, though, too many developers stop there. Delving just a little bit deeper into the language reveals a tremendous amount of new possiblities.
Today I'm going to take a quick look at the basics of PHP classes. A class is an object that is described by the variables and powered by the functions contianed within it. The main benefit of using classes is to have one piece of code that allows you to create any number of instances of that object.
Let's say you wanted to write a class in PHP to define a virtual car. This wouldn't be worth the effort if you only need a single car, but if you need 2 or more, a class is the best way to maintain your variables and be sure that all of your cars will work the same. Some variables you might want in this class would be
$wheels[4],
$doors[2],
$steeringWheel,
$gasPedal,
$brakePedal and
$gearState. Some of yourfunctions would be
function openDoor(),
function accelerate(),
function brake(), and
function turn(). Your functions would be passed variables describing the actions, such as sending
brake() a variable like
$force and sending
turn() the variable
$direction. Lets take a look at the code to create a basic class in PHP:
<?php
class simpleCar {
// member declaration
public $wheels = array('frontLeft','frontRight','rearLeft','rearRight');
public $doors = array('driver','passenger');
public $steeringWheel = 0;
public $gasPedal = 0;
public $brakePedal = 0;
public $gearState = 'park';
public $fuel = 'full';
// method declaration
public function openDoor() {
// code to open a door
}
public function accelerate() {
getFuel();
}
public function brake() {
// code to brake the car
}
public function turn() {
// code to turn the car
}
private function getFuel() {
// inject fuel into engine
}
}
?>
Notice the private function,
getFuel(), that I added at the end of the class. Private variables and functions can only be accessed from within that class. So in the case of
getFuel(), the user could never access it, but a function within the object, such as
accelerate(), is able to call
getFuel() which will then inject fuel into the cars engine. This is how we want the class to act because the car will need to get fuel from the tank, but the user shouldn't ever need to.
So now that our class is ready to go, how do we initialize a new car? The beauty of classes is that once the class is built, creating any number of instances is extremly simple. A new car is defined simply by:
<?php
$myNewCar = new simpleCar();
?>
Now let's expand our simpleCar class to allow us to customize our car. In the "Member Declaration" section, lets add:
$paintColor = 'primer';
$interior = 'cloth';
$cdPlayer = 'no';
$ac = 'no';
Next we'll add a constructor to our class. The constructor will take the 4 customization parameters that we'll be initializing the class with and build a new instance of simpleCar, setting the customization parameters to the values we've given it. Here's what the constructor should look like.
public function __construct($newPaintColor,$newInterior,$newCDPlayer,$newAC) {
$this->paintColor = $newPaintColor;
$this->interior = $newInterior;
$this->cdPlayer = $newCDPlayer;
$this->ac = $newAC;
}
And our code to initialize a new car would be:
<?php
$newPaintColor = 'red';
$newInterior = 'leather';
$newCDPlayer = 'bose-500watt';
$newAC = 'yes';
$myNewCar = new simpleCar($newPaintColor,$newInterior,$newCDPlayer,$newAC);
?>
And there you have it, a simple PHP class to create an object representing a car. As I mentioned earlier, the main benefit here is that you can model as many cars as you need, and you'll need to do for each one is create a new instance.
Have an idea for my next blog post? Looking for any kind of tips or tricks dealing with HTML, CSS, JavaScript, PHP, Perl, ASP, etc? Send your thoughts via our
contact form.
Wed, 2 Jan 2008 7:59AM EST
Here’s another little script I put together while working on my upcoming RSS reader / homepage aggregator application. Everyone knows how to do a basic Ajax style XMLHTTP request lately, but trying to send multiple requests at the same time can be tricky. The simple solution is to create a separate script for each request, but that technique is very inefficient and completely falls apart if you don’t know exactly how many simultaneous requests you are going to be making. In my case, a user of my app will be able to add as many modules to their homepage as they want (well, there may be need to be a limit, but it will be fairly high).
The code below creates an array of XMLHTTP request objects to be executed concurrently. The obvious benefit to this technique over simply running your requests in succession is that one or two slow requests will not stop your visitors from using the application. Each module will load as the response comes back; allowing the slow loading modules to be skipped for the time being.
The code is ready to be dropped directly into your page except for the two areas in red where you’ll have to add code to handle your request responses and errors. You'll most likely be using a DOM function (such as
document.getElementById(myElement).innerHTML = responseText) to write the response to your page. Use the following function call to initiate a request; where "myAjaxScript.php" would be replaced with the path of the script or page you are making a request of:
sendRequest("myAjaxScript.php");
// Create an array to hold the request objects
var requestArray = new Array();
function sendRequest(url) {
var arrayPos = -1;
// Step through the array, looking next available slot
for (var i=0; i<requestArray.length; i++) {
if (requestArray[i].available == 1) {
arrayPos = i;
break;
}
}
// If arrayPos equal -1, request has not been created yet
if (arrayPos == -1) {
// Length of array == next available slot
arrayPos = requestArray.length;
// Create new request by calling newRequest function
requestArray[arrayPos] = new newRequest(1);
}
// If request exists in array[arrayPos]
if (requestArray[arrayPos].xmlhttp) {
requestArray[arrayPos].available = 0;
// Send Request and wait for change
requestArray[arrayPos].xmlhttp.open("GET",url,true);
// Exectue function() when ready state changes
requestArray[arrayPos].xmlhttp.onreadystatechange = function() {
if (typeof(requestArray[arrayPos]) != 'undefined' &&
requestArray[arrayPos].available == 0 &&
requestArray[arrayPos].xmlhttp.readyState == 4) {
// Execute when readyState == 4 (request is complete)
if (requestArray[arrayPos].xmlhttp.status == 200 ||
requestArray[arrayPos].xmlhttp.status == 304) {
/*
Handle the page updage here, using the response
stored in 'requestArray[arrayPos].xmlhttp.responseText'
*/
} else {
/*
Handle an error here
*/
}
requestArray[arrayPos].available = 1;
}
}
if (window.XMLHttpRequest) {
requestArray[arrayPos].xmlhttp.send(null);
} else if (window.ActiveXObject) {
requestArray[arrayPos].xmlhttp.send();
}
}
}
// Create a new request
function newRequest(available) {
this.available = available;
this.xmlhttp = false;
if (window.XMLHttpRequest) { // For non-IE browsers
this.xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // For IE
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Tues, 1 Jan 2008 19:48:00 EST
Just thought I'd share a little PHP script that I wrote recently which takes an RSS feed, parses it and echoes it out on a page. The code itself is very simple and based on PHP5's
simplexml_load_file function. The first section of code takes a predefined RSS feed,
$feed, and loads the feed's XML into the variable
$xml via the simplexml_load_file function. I've also added an
@ in front of the function to suppress the long list of warnings and errors produced by a feed that fails to load. I then check to see that something has, in fact, been loaded into $xml, then begin loading the feed data. Accessing an individual element within an XML document is just as easy as loading the document itself. To access an element in the document, you simply write out the path of the element with each level of the tree separated by "–>". For example,
$site = $xml->channel[0]->title[0]; will load the title of the news feed into the variable
$site. Check out the code and live demo below. This example takes the BBC World News front page RSS and echoes the channel information and the first 20 feed items.
I'm currently working on a
Netvibes-style application that is based off of the use of this function. Check back in a few weeks when I'll be sharing a much more in depth version of the RSS reader.
View a Live Demo »
<?php
$feed = '<Insert Feed URL>';
$xml = @simplexml_load_file($feed);
if($xml) {
$siteTitle = $xml->channel[0]->title[0];
$siteLink = $xml->channel[0]->link[0];
$siteDesc = $xml->channel[0]->description[0];
echo "<strong>$siteTitle<br/>
<a href=\"$siteLink\">
$siteLink
</a>
<br/>$siteDesc</strong><br/><br/>";
for($i=0; $i<20; $i++) {
$itemTitle = $xml->channel[0]->item[$i]->title[0];
$itemLink = $xml->channel[0]->item[$i]->link[0];
$itemDesc = $xml->channel[0]->item[$i]->description[0];
echo "$itemTitle<br/>
<a href=\"$itemLink\">
$itemLink
</a>
<br/>$itemDesc<br/><br/>";
}
} else {
echo "ERROR: Failed to open stream";
}
?>
Mon, 31 Dec 2007 10:12:00 EST
I know there are plenty of these to go around lately, but I recently completed a pure CSS drop-down menu and I thought I'd share it with the world. JavaScript drop-down menus tend to give me more headaches than they're worth and I haven't been able to find a pure CSS menu that suits my needs (mainly cross-browser compatibility), so I set out to build my own; turns out it wasn't nearly the adventure I thought it was going to be.
By using the typical IE HTML hacks ("<!--[if IE 7]>" and "<!--[if lte IE 6]>"), I’ve been able to get drop-down to work well in IE6, IE7, Firefox, Opera, Safari, Mac Firefox and Netscape 8. I’ve tried to make the code as clear and self-explanatory as possible, but if you have any questions, feel free to ask them in the comments section.
View a live demo »
Insert the following code into the header of your web page:
<style type="text/css">
/*-----------------------------------------------------------
Pure CSS Drop-down Menu
Last Updated: 12/31/2007 by Justin Spegele
Author: Justin Spegele
Spegele Design and Development
http://www.spegele.com/
This code is free to modify and use for any purpose, as
long as proper credit is given to the original designer.
----------------------------------------------------------- */
/* Overarching Menu
-----------------------------------*/
.cssnav {
position:relative;
z-index:1000;
font-size:12px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-weight:bold;
text-align:center;
}
.cssnav ul {
padding:0;
margin:0;
list-style-type:none;
}
.cssnav ul ul {
width:149px;
text-align:left;
}
/* Main list
-----------------------------------*/
.cssnav li {
float:left;
width:150px;
position:relative;
}
/* First Level
-----------------------------------*/
/* Links */
.cssnav a, .cssnav a:visited {
display:block;
text-decoration:none;
color:#fefefe;
border:1px solid #fff;
border-width:1px 0px 1px 1px;
background:#467aa7;
line-height:25px;
}
/* Links on hover */
.cssnav a:hover, .cssnav ul ul a:hover{
color:#fff;
background:#80b0da;
}
.cssnav :hover > a, .cssnav ul ul :hover > a {
color:#fff;
background:#80b0da;
}
/* Second Level
-----------------------------------*/
/* Links */
.cssnav ul ul a, .cssnav ul ul a:visited {
background:#578bb8;
line-height:1em;
padding:5px 10px;
width:128px;
border-width:0 1px 1px 1px;
}
/* Links on hover */
.cssnav ul ul a:hover {
background:#80b0da;
}
/* Visibility */
.cssnav ul li:hover ul, .cssnav ul a:hover ul{
visibility:visible;
}
/* Third Level
-----------------------------------*/
/* Links */
.cssnav ul ul ul a, .cssnav ul ul ul a:visited {
background:#578bb8;
}
/* Links on hover */
.cssnav ul ul ul a:hover {
background:#80b0da;
}
/* Positioning */
.cssnav ul ul ul{
left:150px;
top:-1px;
}
.cssnav ul ul ul.left {
left:-150px;
}
/* Visibility */
.cssnav ul :hover ul ul{
visibility:hidden;
}
.cssnav ul :hover ul :hover ul{
visibility:visible;
}
/* All Sub Levels
-----------------------------------*/
/* Default visibility */
.cssnav ul ul {
visibility:hidden;
position:absolute;
top:26px;
left:0;
border-top:1px solid #fff;
}
/* IE Table
-----------------------------------*/
.cssnav table {
position:absolute;
top:0;
left:0;
border-collapse:collapse;
}
</style>
Insert the following code into the body of your web page:
<!-- *******************************************************
Pure CSS Drop-down Menu
Last Updated: 12/31/2007 by Justin Spegele
Author: Justin Spegele
Spegele Design and Development
http://www.spegele.com/
This code is free to modify and use for any purpose, as
long as proper credit is given to the original designer.
http://www.spegele.com/
******************************************************** -->
<div class="cssnav">
<ul>
<li><a href="#">Home</a></li>
<li>
<a href="#">Pages
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul>
<li><a href="#" title="Page 1">Page 1</a></li>
<li><a href="#" title="Page 2">Page 2</a></li>
<li><a href="#" title="Page 3">Page 3</a></li>
<li><a href="#" title="Page 4">Page 4</a></li>
<li>
<a class="drop" href="#" title="Page5">Page 5
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul>
<li><a href="#" title="Sub Page 1">Sub Page 1</a></li>
<li><a href="#" title="Sub Page 1">Sub Page 2</a></li>
<li><a href="#" title="Sub Page 1">Sub Page 3</a></li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li>
<li>
<a href="#">Links
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul>
<li><a href="#" title="Link 1">Link 1</a></li>
<li><a href="#" title="Link 2">Link 2</a></li>
<li><a href="#" title="Link 3">Link 3</a></li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li>
<li>
<a href="#">More Links
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul>
<li><a href="#" title="More Links 1">More Links 1</a></li>
<li>
<a class="drop" href="#" title="More Links 2">More Links 2
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul class="left">
<li>
<a href="#" title="More Sub Links 1">More Sub Links 1</a>
</li>
<li>
<a href="#" title="More Sub Links 2">More Sub Links 2</a>
</li>
<li>
<a href="#" title="More Sub Links 3">More Sub Links 3</a>
</li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li>
<li><a href="#" title="More Links 3">More Links 3</a></li>
<li><a href="#" title="More Links 4">More Links 4</a></li>
<li><a href="#" title="More Links 5">More Links 5</a></li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li>
</ul>
</div>