Development

Five Star Linked Data

The vision of the Semantic Web is to create both connected and interlinked data which can be shared and reused by all. In 2006, Sir Tim Berners-Lee introduced a notion of linked data and the best practices for creating and sharing on the Web. To encourage people (and government) to share data he additionaly developed a rating system:

* Available on the web in any format, but with an open licence
** Available as machine readable structured data such as Excel
*** As for two stars, but in an open format such as CSV
**** As for three stars but using open standards from W3C to identify
***** All the above but additionally linking your data to other peoples to provide context

There are some badges available here to display on your site if you wish to display your commitment
Cafepress has official W3C merchandise available here

In the holiday downtime it is good to think about some of the ways we can make a real difference in amongst those cool drinks at the beach (or snow shovelling in the Northern Hemisphere)

Five Star Linked Data Read More »

PHP URL Shortening


A current Twitter related project involves quite a few URLs and because Twitter limits you to only 140 characters per post shortening a link can be very rewarding.

There are a multitude of URL shortening services on the internet and whilst perhaps not producing the shortest links, TinyURL.com requires no account in order to use it via PHP which makes for a very simple query:
function getTinyUrl($url) {
return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}

bit.ly is another popular URL shortener, however it does require an easily obtainable API key. The code is below:
function getBitly($url) {
$query = file_get_contents("http://api.bit.ly/v3/shorten?login=YOUR_LOGIN&;apiKey=YOUR_APIKEY&longUrl=".$url."&format=xml");
$element = new SimpleXmlElement($query);
$bitlyurl = $element->data->url;
if($bitlyurl){
return $bitlyurl;
} else {
return '0';
}
}

Don’t forget to change YOUR_LOGIN and YOUR_APIKEY to your own values. I’m sure you don’t need any help with usage, but as always comment if you have any issues.

PHP URL Shortening Read More »

PHP Arrays

Recently I had to refactor a few quite old CRON jobs which made extensive use of arrays within loops.

As usual with old code I had to brush up a little as a reminder so thought I would summarise a few quick notes:

sort() and rsort() are for sorting indexed arrays
asort() and arsort() are for sorting associative arrays
ksort() and krsort() are for sorting associative arrays by key
array_multisort() is for sorting multiple related arrays and multidimensional arrays

The PHP sort() function sorts values contained within an indexed array in ascending order.
This means that A-Z, and 0-9. Uppercase letters come before lowercase letters, and all letters come before numbers.

$testArray = array( 1, 2, 3, 'a', 'b', 'c', 'A', 'B', 'C' );
sort( $testArray );

// Displays "A B C a b c 1 2 3"
foreach ( $testArray as $value ) echo "$value ";

rsort() works exactly the same as sort(), except that it sorts in descending order.

$testArray = array( 1, 2, 3, 'a', 'b', 'c', 'A', 'B', 'C' );
rsort( $testArray );

// Displays "3 2 1 c b a C B A"
foreach ( $testArray as $value ) echo "$value ";

Sorting associative arrays using asort() and arsort()

sort() and rsort() are great for indexed arrays where you usually do not care about the relationship between keys and values; however with an associative array they can cause problems:

$book = array( "title" => "Lord Of The Rings", "author" => "J.R.R. Tolkien", "year" => 1954 );
sort( $book );

// Displays "Array ( [0] => J.R.R. Tolkien [1] => Lord Of The Rings [3] => 1954 )"
print_r( $book );

As you can see, the sort() function has reindexed the array with numeric indices and in the process destroyed the original string indices of “title”, “author”, and “year”.

To sort values in an associative array whilst preserving keys, use asort() and arsort() instead as these functions preserve not only the keys, but also the relationship between keys and their values.

$book = array( "title" => "Lord Of The Rings", "author" => "J.R.R. Tolkien", "year" => 1954 );
asort( $book );

// Displays "Array ( [author] => J.R.R. Tolkien [title] => Lord Of The Rings [year] => 1954 )"
print_r( $book );

Sorting associative arrays by key using ksort() and krsort()

As well as sorting an associative array by value it can also be sorted by key. ksort() sorts the elements in ascending key order, while krsort() sorts in descending key order.

Just like asort() and arsort() these functions will preserve the relationship between key and value.

$book = array( "title" => "Lord Of The Rings", "author" => "J.R.R. Tolkien", "year" => 1954 );
ksort( $book );

// Displays "Array ( [author] => J.R.R. Tolkien [title] => Lord Of The Rings [year] => 1954 )"
print_r( $book );

krsort( $book );
// Displays "Array ( [year] => 1954 [title] => Lord Of The Rings [author] => J.R.R. Tolkien )"
print_r( $book );

So far, so good, – so lets move onto multidimensional arrays.

Sorting multiple arrays and multidimensional arrays with array_multisort()

The PHP array_multisort() function sorts multiple related arrays in one run whilst preserving the relationships between the arrays, and it can also sort multidimensional arrays.

$directors = array( "James Cameron", "Ethan Cohen", "Christopher Nolan" );
$titles = array( "Aliens", "The Big Lebowski", "Inception" );
$years = array( 1986, 1998, 1973 );

array_multisort( $directors, $titles, $years );

print_r( $directors );
echo "<br />";
print_r( $titles );
echo "<br />";
print_r( $years );
echo "<br />";

Outputs:

Array ( [0] => Christopher Nolan [1] => Ethan Cohen [2] => James Cameron )
Array ( [0] => Inception [1] => The Big Lebowski [2] => Aliens )
Array ( [0] => 2010 [1] => 1998 [2] => 1986 )

Notice how the array_multisort() function has sorted the values in $directors in ascending order and then sorted the other 2 arrays so that the element order matches the order of the sorted $directors array.

Sorting multidimensional arrays

If you pass a multidimensional array to array_multisort() then it sorts by looking at the first element of each nested array.

If 2 elements have the same value then it sorts by the second element, and so on. For example:

$movies = array(
array(
"director" => "Ethan Cohen",
"title" => "The Big Lebowski",
"year" => 1998
),
array(
"director" => "James Cameron",
"title" => "Aliens",
"year" => 1986
),
array(
"director" => "Christopher Nolan",
"title" => "Inception",
"year" => 1973
),
array(
"director" => "James Cameron",
"title" => "Titanic",
"year" => 1997
)
);

array_multisort( $movies );
echo "<pre>";
print_r( $movies );
echo "</pre>";

Outputs:

Array
(

[0] => Array
(
[director] => Christopher Nolan
[title] => Inception
[year] => 1973
)
[1] => Array
(
[director] => Ethan Cohen
[title] => The Big Lebowski
[year] => 1998
)

[2] => Array
(
[director] => James Cameron
[title] => Aliens
[year] => 1986
)

[3] => Array
(
[director] => James Cameron
[title] => Titanic
[year] => 1997
)
)

So as you can see the array sorting functions in PHP are quite powerful and flexible. This brief post only covers a few options, there are more functions if you require them. Here is a great place to start.

PHP Arrays Read More »

Everything about UTF-8

Filed under PHP, but obviously much more than that.

In an update to this post, it is time for a revisit of UTF-8.

In a post entitled “Everything you always wanted to know about UTF-8 (but never dared to ask)” the good folk at the iBuildings TechPortal have Juliette Reinders Folmer speak on a variety of topics.

“…In this talk I will cover UTF-8 from basic linguistics, through client-side aspects to all the steps you need to take to tackle the most common (and some more obscure) issues when using UTF-8 in a database driven PHP application…”

Check it out here.

Everything about UTF-8 Read More »

Simple PHP Best Practices

This post is intended to make you think a little bit more about some of the habits you may have formed whilst programming. It is not the nirvana of programming, nor best practice, just a few little ideas to help you along the way.

1. Use descriptive variable names
Arguably this is the hallmark of the inexperienced or just plain poor programmer. Using variables names such as $x or $y makes a major sacrifice in readability for a negligible performance improvement.
Remember, variable names are cheap whilst programmer time is not.

2. No commented out code
Sure, commenting out code makes sense if you do not use a revision control system (like CVS/SVN/Git/etc) however – why on earth are you not using a revision control system?
Leaving commented code behind tends to clutter files and reduces readability, – especially in those hard times on a console and don’t have the luxury of an editor with syntax highlighting and large resolution.

3. Write control structures as you would say them
It is all too easy to make control structures (if, switch, while, etc…) unreadable. An easy trick to improve readability is to read it to yourself, from start to finish; this forces you to read it anew and clears up strange comparisons such as: ‘!$security_check===false’.

4. Use single quotes (‘) by default and double quotes only when you want to put variables in your string
It’s the little things…

Simple PHP Best Practices Read More »

Exporting a MySQL Database Schema as XML

Dumping a database schema is a an often required quick task. This script will read the schema from a MySQL database, and output it XML to describe it.


<?php
// Define a few constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");
define("DB_NAME", "example");

// Lets connect to the db
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");

// Choose a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select examples");
// Return all of the available tables
$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );

$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}

$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";

// Now iterate through each table and return the fields
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );

while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}

$output .= "</table>";
}

$output .= "</schema>";

// Notify the browser the type of file being dealt with
header("Content-type: text/xml");
// Display the XML to describe the schema
echo $output;

// Dont forget to close the connection
mysql_close($dbhandle);
?>

Remember, this is an example, and real world code should escape characters, follow best security practices etc. Proof of concept code here, – not a snippet to put live.

Exporting a MySQL Database Schema as XML Read More »