Monthly Archiv: August, 2010

PHP to Yahoo Messenger

Package:
PHP to Yahoo Messenger
Summary:
Send an instant message to Yahoo Messenger user
Groups:
Chat, PHP 5, Web services
Author:
Halim PN
Description:
This class can be used to send an instant message to Yahoo Messenger user.

It can send HTTP requests to the Yahoo Messenger Web server to authenticate as a given user and then sends a message to another given user.


ODBC on The Fly

Package:
ODBC on The Fly
Summary:
Connect and query Microsoft Access databases
Groups:
Databases, PHP 5, Windows
Author:
Osama Salama
Description:
This class can be used to connect and query Microsoft Access databases.

It takes the path of a Microsoft Access database file and computes suitable a DSN string to establish a connection to the database using ODBC extension on Windows.

The class can also execute a given SQL query to the connected database and return the whole result set in an array.


Simple Singleton and Multiton Class

Package:
Simple Singleton and Multiton Class
Summary:
Create and manage one or more singleton objects
Groups:
Design Patterns, PHP 5
Author:
Andrei Alexandru
Description:
This package can be used to create and manage one or more singleton objects.

There is one class that can manage one singleton object, assuring that only one instance of the class is created.

Another class can manage multiple singleton objects which are distinguished by name.


Folder_DetailView

Package:
Folder_DetailView
Summary:
Show a list of nested folders as collapsible tree
Groups:
HTML, PHP 5
Author:
Michael J. Fuhrman
Description:
This package can be used to show a list of nested folders as collapsible tree.

It can generate HTML and JavaScript to show a list of nested folders that expand and collapse when the user clicks on folder entries.


[Free] New PDF Conversion Software: Create a PDF Ebook or Convert Documents to the PDF Format

Do you fancy creating your own PDF ebook? Or perhaps you simply want to convert a document into the PDF format? Check out the newest entry in the Free PDF Converters, Editors and Printer Drivers page. There are now 11 PDF conversion tools on that page, so even if you don't like the latest addition, there are many others to choose from. Besides, they are all free: you can get them all if you like.

A Simple Movie Search App w/ jQuery UI

In this tutorial, we are using jQuery UI’s autocomplete widget, to build a simple AJAX movie search form. The script is going to use TheMovieDatabase.org‘s free API, to provide auto suggestions against a vast database of movie titles.

For those of you who might not be familiar with TMDb.org, this is an open, community driven movie database. It is similar to IMDb, which you’ve probably heard about, but also provides a number of useful API’s for developers.

Prerequisites

Before being able to use the API, you need to get a free developer key from TMDb after a quick registration. After this, remember to copy your key to movieInfo.php from the download archive.

Step 1 – XHTML

The markup consists of  the two main div containers – #logo and #holder. The former holds the icon and the logo text in the form of transparent PNG images (defined as backgrounds to the respective divs), while the latter contains the search form and the submit button.

movieApp.html

<div id="page">

    <div id="logo">
        <div id="icon"></div>
        <div id="movieAppLabel"></div>
    </div>

    <div id="holder">
    	<form action="http://www.themoviedb.org/search" method="post" target="_blank">
            <fieldset>
            	<input type="text" id="movieName" name="search" />
            </fieldset>
        </form>
        <a href="#" class="button">Submit</a>
    </div>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script src="script.js"></script>

Notice that the action attribute of the form is pointed at TMDB’s search page. The search terms are passed via POST with the #movieName text field. You can test it by filling in a movie name and submitting the form.

Lastly in the page are included jQuery, jQuery UI and our own script file. We are using jQuery UI’s autocomplete widget to display a drop down list of movie titles which are fetched from TMDb’s API. You can see the markup that is generated by the widget below.

<input class="ui-autocomplete-input"/>
<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all">
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 1</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 2</a>
  </li>
  <li class="ui-menu-item">
    <a class="ui-corner-all">item 3</a>
  </li>
</ul>

This code is generated automatically by the widget and appended before the closing body tag.

Simple Movie Search App

Simple Movie Search App

Step 2 – PHP

When you start typing a movie title in the text box of the form, an AJAX request is sent to moveInfo.php. This script sends a search request to TMDb’s API, with our developer key. The service returns a JSON object with suitable movie titles. The script processes them and outputs them back as a response to the AJAX request.

Lets take a closer look at how this works.

movieInfo.php

/**
 *	Define your API key below. To obtain one, visit
 *	http://www.themoviedb.org/account/signup
 */

$api_key = '...';

// If the request was not issued by AJAX, or
// the search term is missing, exit:

if(!$_SERVER["HTTP_X_REQUESTED_WITH"] || !$_GET['term']){
	exit;
}

include 'tmdbAPI/TMDb.php';

$tmdb = new TMDb($api_key);

// Send a search API request to TMDb,
// and parse the returned JSON data:

$json = json_decode($tmdb->searchMovie($_GET['term']));

$response = array();

$i=0;
foreach($json as $movie){

	// Only movies existing in the IMDB catalog (and are not adult) are shown

	if(!$movie->imdb_id || $movie->adult) continue;
	if($i >= 8 ) break;

	// The jQuery autocomplete widget shows the label in the drop down,
	// and adds the value property to the text box.

	$response[$i]['value'] = $movie->name;
	$response[$i]['label'] = $movie->name . ' <small>(' . date('Y',strtotime($movie->released)).')</small>';
	$i++;
}

// Presenting the response as a JSON object:

echo json_encode($response);

Luckily for us, there is a PHP class available, that handles all communication with the TMDb API. We just need to include it into the page, and provide the developer API key we received from TMDb. The search terms, that the user has entered into the search box, are available in $_GET['term']. Calling the searchMovie() method with these terms, will yield a JSON object, containing all kinds of information about the movies that match our search criteria. You can see a sample response below.

[{
    "score": 8.750235,
    "popularity": 3,
    "translated": true,
    "adult": false,
    "language": "en",
    "name": "The Hitchhiker's Guide to the Galaxy",
    "alternative_name": "The Hitchhikers Guide to the Galaxy",
    "movie_type": "movie",
    "id": 7453,
    "imdb_id": "tt0371724",
    "url": "http://www.themoviedb.org/movie/7453",
    "rating": 6.8,
    "certification": "PG",
    "overview": "Mere seconds before the Earth is to be demolished by an alien construction crew, Arthur Dent is swept off the planet by his friend Ford Prefect, a researcher penning a new edition of \"The Hitchhiker's Guide to the Galaxy.\"",
    "released": "2005-04-20",
    "posters": [{
        "image": {
            "type": "poster",
            "size": "original",
            "height": 1000,
            "width": 675,
            "url": "http://hwcdn.themoviedb.org/posters/16e/4bcc96cd017a3c0f2600016e/the-hitchhiker-s-guide-to-the-galaxy-original.jpg",
            "id": "4bcc96cd017a3c0f2600016e"
        }
    }],
    "version": 22,
    "last_modified_at": "2010-07-19 22:59:02"
}]

The response contains the title of the movie, an overview, release date, a corresponding IMDB id, and even posters and fan art. We do not need most of this information, so PHP reduces it only to a title and a release year, after which outputs it in the form of a JSON object, ready to be used by the autocomplete. This brings us to the next step.

Step 3 – jQuery

As you know, jQuery comes with a lot of useful functionality in the form of plugins. There is also a dedicated extension of the library, for building user interfaces, known as jQuery UI. It gives developers widgets, which are ready for use and easy to customize. One of these widgets is the new autocomplete widget, introduced in the newer versions of the library.

Lets take a look at how it is used.

script.js

$(document).ready(function(){

	// Caching the movieName textbox:
	var movieName = $('#movieName');

	// Defining a placeholder text:
	movieName.defaultText('Type a Move Title');

	// Using jQuery UI's autocomplete widget:
	movieName.autocomplete({
		minLength	: 5,
		source		: 'movieInfo.php'
	});

	$('#holder .button').click(function(){
		if(movieName.val().length && movieName.data('defaultText') != movieName.val()){
			$('#holder form').submit();
		}
	});
});

// A custom jQuery method for placeholder text:

$.fn.defaultText = function(value){

	var element = this.eq(0);
	element.data('defaultText',value);

	element.focus(function(){
		if(element.val() == value){
			element.val('').removeClass('defaultText');
		}
	}).blur(function(){
		if(element.val() == '' || element.val() == value){
			element.addClass('defaultText').val(value);
		}
	});

	return element.blur();
}

To create an autocomplete, we just need to call the autocomplete() method. It takes a number of optional parameters. The most important ones are minLength (which prevents request to the server from being fired before a certain number of characters has been typed) and source, which determines the data that is shown in the drop down list.

Source can take either an array with strings, a URL (to which an AJAX request will be sent) or a callback function. In our case, the URL of movieInfo.php will suffice.

Here is a sample response, which is returned by movieInfo.php (this JSON object was compiled after a request to TMDb’s API for “Hitchhiker’s guide“).

[{
    "value": "Hachiko: A Dog's Story",
    "label": "Hachiko: A Dog's Story <small>(2009)<\/small>"
},
{
    "value": "Teenage Hitch-hikers",
    "label": "Teenage Hitch-hikers <small>(1975)<\/small>"
},
{
    "value": "The Hitchhiker's Guide to the Galaxy",
    "label": "The Hitchhiker's Guide to the Galaxy <small>(2005)<\/small>"
},
{
    "value": "The Hitch-Hiker",
    "label": "The Hitch-Hiker <small>(1953)<\/small>"
}]

Each object in the array contains a value and a label property. The label is only shown in the dropdown list, while the value is inserted into the textbox once the item is selected.

Custom Styled jQuery UI Autocomplete

Custom Styled jQuery UI Autocomplete

Step 4 – CSS

Now that all the markup is generated and is in place, it is time to start beautifying.

styles.css – Part 1

#page{
	width:600px;
	margin:150px auto 0;
}

/* Logo */

#logo{
	width:380px;
	position:relative;
	height:90px;
	margin:0 auto;
}

#icon{
	width:80px;
	height:86px;
	background:url('img/icon.png') no-repeat;
	float:left;
}

#movieAppLabel{
	width:268px;
	height:58px;
	background:url('img/logo_txt.png') no-repeat;
	position:absolute;
	right:0;
	top:18px;
}

/* The Search Box & Holder */

#holder{
	width:530px;
	height:145px;
	background:url('img/holder.png') no-repeat center center;
	margin:30px auto;
	position:relative;
}

#holder fieldset{
	position:absolute;
	top:52px;
	left:40px;
	border-bottom:1px solid #fff;
}

#holder input{
	font-family:'Myriad Pro',Arial,Helvetica,sans-serif;
	border:none;
	border-bottom:1px solid #bbb;
	background:none;
	color:#8D8D8D;
	font-size:20px;
	padding:4px 0;
	width:250px;
	text-shadow:1px 1px #fff;
	outline:none;
}

In the first part of the code, we style the #logo, and the #holder divs. The shutter icon and the logo text are defined as backgrounds to the #icon and #movieAppLabel divs respectively. Relative positioning is applied to the #holder so that it is easier to position the input box and the submit button.

styles.css – Part 2

fieldset{
	border:none;
}

/* The Blue Button */

a.button{
	background:url('img/buttons.png') no-repeat;
	width:105px;
	height:37px;
	position:absolute;
	top:52px;
	right:42px;
	text-indent:-9999px;
	overflow:hidden;
	border:none !important;
}

a.button:hover{
	background-position:left bottom;
}

/* Styling the markup generated by the autocomplete jQuery UI widget */

ul.ui-autocomplete{
	width:250px;
	background-color:#f5f5f5;
	border:1px solid #fff;
	outline:1px solid #ccc;
}

ul.ui-autocomplete li{
	list-style:none;
	border-bottom:1px solid #e0e0e0;
	border-top:1px solid #fff;
}

ul.ui-autocomplete li:first-child{
	border-top:none;
}

ul.ui-autocomplete li:last-child{
	border-bottom:none;
}

ul.ui-autocomplete li a{
	color:#999;
	border:none !important;
	text-decoration:none !important;
	padding:10px 17px;
	display:block;
}

#ui-active-menuitem{
	background-color:#fff;
	color:#666;
	cursor:pointer;
}

jQuery UI does come with its own styles, however they are rather clunky and do not fit well into the current design. This is why we are applying a number of rules (starting from line 23), which apply a custom design to the autocomplete widget. The structure of the widget is basically an unordered list, with each of the suggested items being a hyperlink in a li element. With this in mind (and after looking up the appropriate class names from the code in step one) we can safely style the drop down list and perfectly blend it with the rest of the design.

With this our Simple Movie Search App is complete!

To Wrap it Up

You can modify this script to use any kind of api and data. This can be a powerful tool, as it might assist users in typing search terms that they may not normally think of themselves. For example providing your product names as search suggestions, may be an effective tactic to expose more of your merchandise and improve sales.

What do you think? How would you improve this app?

amba XML document

Package:
amba XML document
Summary:
Extend the DOM XML classes
Groups:
PHP 5, XML
Author:
Alexey V Ryazhskikh
Description:
This package extends the DOM XML classes to provide additional functionality.

The DOM Document extension class can return the document root element, add a new node to the end of the document, select nodes that match a XPath expression, call a function for a list of elements and transform a document using XSL.

The DOM element extension class can get XML for the owner document, get the node XPath, get child nodes, select child nodes that match a XPath expression, get the parent and sibling nodes, get and set attributes by name, copy attributes, add child nodes and character data, import and export nodes to and from another document, set and get the inner XML of a node, call a function for nodes that map a XPath expression, etc..

Standard DOMDocument has rich functionality, but it is not handy enough. XMLDocument is extension of standard PHP DOMDocument and DOMElement.


This project contains two classes for easy create, navigate and process XML documents.

Main features is:

* SelectSingleNode and SelectNodes - node related functions works like same functions in C#.
* Inner XML getting/setting - easy and in one line.
* Chain style to create new node sets.
* Functions for frequently used actions: copy attributes, delete all childs etc.

Usage sample:

$doc = new XMLDocument("<Users/>");
$doc->getRoot()->addNode('User')
->setAttribute('Active', 'true')
->addNodeWithCData('Name', 'John')
->getParent()->getParent()
->addNode('User')
->setInnerXML('<Name><![CDATA[Peter]]></Name>');
echo $doc->saveXML();

Result:

<Users>
<User Active="true">
<Name><![CDATA[John]]></Name>
</User>
<User>
<Name><![CDATA[Peter]]></Name>
</User>
</Users>

See Samples for more details.


Powered by Gewgley