Using JSON with PHP

In a recent programming task I’ve been working on I’ve needed to transfer some data, in the form of arrays, from one PHP page to another via hidden input fields in a form. I’ve used JSON for this task. More information on JSON is available at the official website.

Some of things I’ve learnt are:

Check to ensure the JSON functions are available

The JSON functions in PHP are provided by an extension that is only bundled with PHP version 5.2 and above. If you don’t have that specific version you can compile and include the php-json extension yourself, or use the JSON-PHP library which is written in pure PHP and doesn’t require any compilation.

Detecting which library to use is easy

To ensure your code doesn’t cause problems you can construct it in such a way that it detects if the php-json extension is available and if not use the json-php library using code like this:


if(!function_exists('json_encode')) {
    // PHP pre 5.2 or the library isn't installed
    // include the alternate library
    require_once('path/to/library/JSON.php');
    $json_services = new Services_JSON();
    $encoded = $json_services->encode($my_var);

} else {
    $encoded = json_encode($my_var);
}

The same technique will work for decoding as well:


if(!function_exists('json_encode')) {
    // PHP pre 5.2 or the library isn't installed
    // include the alternate library
    require_once('path/to/library/JSON.php');
    $json_services = new Services_JSON();
    $my_var = $json_services->decode($encoded);

} else {
    $my_var = json_decode($encoded);
}

Including the data in a form requires some extra work

To include the data in the form, you need to change the double quotes (”) in the encoded data into single quotes (’). Otherwise the generated HTML will be invalid. You can do this quite easily using the str_replace function. Remember to do the reverse replacement before decoding the data.

Ensure you get the variable type you expect

By default an array will be decoded as an object. This can make using it in your code a little bit more complicated. Fortunately the json_decode function will take an additional boolean operator to return an array, and you can use variable type casting when using the json-php library. For example:


if(!function_exists('json_encode')) {
    // PHP pre 5.2 or the library isn't installed
    // include the alternate library
    require_once('path/to/library/JSON.php');
    $json_services = new Services_JSON();
    $my_array = (array) $json_services->decode($encoded);

} else {
    $my_array = json_decode($encoded, TRUE);
}

A list of category feeds on a page in WordPress

A blog implementation project I’m working on at the moment is using the categorisation capability of WordPress to support SDI for our users. By using categories our users can either subscribe to the RSS feeds for each category, or subscribe to a mailing list powered by the excellent Subscribe2 plugin and select specific categories.

In this way our users are in control of the information they receive and can filter out, at a broad level, those posts that are of no interest to them.

We have our categories listed in the sidebar on our site. The wp_list_categories template tag has the ability to output a link to the RSS feed for a category but the output didn’t fit in our layout. With this in mind I needed to come up with a different way of displaying the information.

Rather than create a plugin I decided to use the a custom page template instead. In this way I could construct a page that I could edit the text of the page using the standard tools, and I could also create a list of RSS feeds dynamically, without the need to go through creating a plugin.

I created a custom page template, basically a copy of the standard page template, and then added the following code into the appropriate place.


< ?php
// Get the list of categories
$categories = get_categories('type=post&hide_empty=0&orderby=id');
$site_url = get_option('siteurl');

// Output the list
print '<ul>';

foreach($categories as $category) {
  print '<li><a href="' . $site_url . '/category/' . $category->category_nicename . '/feed/' . '" ';
  print 'title="Direct link to the RSS feed">';
  print $category->name . '</a>';
  print '<a href="' . $site_url . '/category/' . $category->category_nicename . '/feed/' . '" ';
  print 'title="Direct link to the RSS feed" style="text-decoration: none">';
  print ' <img src="';
  bloginfo('template_url');
  print '/images/feed-icon-14x14.png" height="14" width="14" alt="" border="0"/></a></li>' . "\n";
}

print '';
?>

Users can select from the generated list, the URLs to the RSS feeds that are of interest to them.

Fixing Random freezes in Ubuntu 8.04

Icebergs in GreenlandI’ve been using the Ubuntu Linux 8.04 release (Hardy Heron) for a while now. Lately I’ve been experiencing this really odd behaviour. While using OpenOffice.org applications, like Writer, if I swapped between the OpenOffice.org window and the window of another application, sooner or later my entire system would freeze. At the time the only thing I could do was turn it off, and then turn it back on again. The severe downside of this was that I’d typically lose any unsaved work.

I did some investigating on the Internet and stumbled across this post in the OpenOffice.org Community Forum. While I disagree with the idea of replacing the Ubuntu supplied OpenOffice.org packages with ones from another source, it did confirm that other people have been experiencing this type of issue.

So I wasn’t alone, which is encouraging in an odd sort of way while you’re trying to solve an issue you’re experiencing. It neatly answers the “Is it just me?” question.

Further investigation turned up this post on the Compiz Fusion Forum. What it suggests is that there is a potential issue with the proprietary NVidia drivers and the Focus Animation and potentially the Water Effect plugins.

To change the Compiz Fusion settings I followed this procedure:

  1. Click the System main menu item
  2. Click the Preferences sub menu item
  3. Click the Advanced Desktop Effect Settings menu item
  4. Click the Effects button under the Categories heading in the left hand pane
  5. Click the Animations button under the Effects heading in the right hand pane
  6. Click the Focus Animation tab
  7. Click the New button
  8. Leave all the options in the Edit window at their defaults and click the Close button
  9. Select any other entries in the Animation Selection list and click Delete button
  10. Close the CompizConfig Settings Manager window

If the Advanced Desktop Effect Settings menu item isn’t listed, ensure the compizconfig-settings-manager package is installed.

The other thing that the post mentioned is the Magic SysRq key, something I’ve never come across before. I did a search and found this article in Wikipedia. From the article:

The magic SysRq key is a key combination in the Linux kernel which, if the CONFIG_MAGIC_SYSRQ option was enabled at kernel compile time, allows the user to perform various low level commands regardless of the system’s state using the SysRq key. It is often used to recover from freezes, or to reboot a computer without corrupting the filesystem.

With this in mind, if it ever happens again, which it hasn’t based on my experiences so far. I should be able to get back to the system without forcing a reboot.

It is odd though that I only experienced this issue when using the OpenOffice.org applications. Which would seem to suggest the problem I was experiencing is more subtle than just an issue with drivers and Compiz Fusion.

The photo “Icebergs in Greenland” was uploaded to Flickr by Nick Russill and found using the everystockphoto.com search engine.

This blog turned two years old yesterday

Yesterday marked a milestone for this blog. It is two years since I started this blog, and called it home for my little piece of the Internet. Looking back it is interesting to see how the voice of the blog has changed.

It started life as a place to write about my explorations with technology while I was part of the RUBRIC project. The programming language I wrote most about then was Python, and that was mostly all I wrote about.

I then moved to South Australia and took up a position as the Systems Librarian at the University of Adelaide. My posts started to be more about Ubuntu Linux, which I’ve been using full time on my laptop for a number of years now, programming in Perl and my photography.

Now I’m working in the Office of Research at Flinders University. I’m now programming in PHP and exploring so called “Web 2.0″ technologies such as AJAX in my development work. I’ve also recently released my first WordPress plugin, WordPress Blogroll to Google CSE, and I’m working on another with the kind people at the Libraries Interact blog.

My professional interests have evolved over the years as well. Moving away from programming, although I think I’ll always be interested in development work, to project management and a larger view of the higher education sector.

It has been an interesting journey to see aspects of my life written about for the world to see, especially those that have changed, or those that are challenging to put out there like my photos.

As with all posts of this type, it is time for some obligatory stats:

It has been a great experience writing my own blog, and I look forward to seeing what the next year will bring. Many thanks also to those that have posted comments, it is rewarding to see that people are getting some value from what I write about.

    Removing Wine application entries on Ubuntu

    I’ve been using Wine on my laptop running Ubuntu for a while now. I posted about it a while back. Wine came in very handy when I had an MP3 file that I needed to trim.

    This morning I tried some software under using Wine and was disappointed when the software didn’t meet my needs, so I uninstalled it. I was disturbed to notice the entries for the application in my Gnome Applications menu stayed.

    Searching the Internet revealed this post on the Ubuntu Forums website. The solution is essentially:

    1. Open a new terminal window
    2. Navigate to the following folder
      ~/.local/share/applications/wine/Programs/
    3. Delete the .desktop files for the application

    If the program is in a folder on the menu, you may need to navigate further down the tree.

    Alternatively you can use the File Browser if you prefer. The .local directory is in your home directory. If you can’t see it use the <ctrl>+h keyboard shortcut to show hidden files.

    Posted in Linux, Musings. Tags: , . No Comments »

    A yellow rose

    A few weeks ago we went into the city here in Adelaide and as usual I took my camera with me. I took a number of close up photos of the flowers in the garden beds around the Adelaide Oval. I thought some of them may look good if I changed the background to black and white and left the rose in colour.

    Below is my first attempt at this. I used the GIMP on Ubuntu Linux and a Bamboo tablet from Wacom. I’d tried this technique using just a mouse and the results not as good as using a tablet. Using the tablet was also easier on my wrist.

    Initially I tried the Foreground Select tool, but found the rose was too complex. Either that or I wasn’t using the tool correctly. In the end I followed this tutorial and I think the resulting image is interesting.


    (Click image for larger version)

    Posted in Photos. Tags: , . No Comments »

    Trimming and fixing an MP3 file

    I had an issue with a MP3 audio file today. Essentially the was this odd sharp beep noise at the beginning of the track, and it would fail to play the first time you tried. This happened in both Rhythmbox and Totem, which isn’t surprising as I believe they both use the GStreamer framework for decoding media streams.

    I fixed the MP3 file by using the mpTrim application to trim off the first second of the file. This is a Windows only application, which fortunately worked flawlessly under Wine on my laptop running Ubuntu Linux.

    Anyone who has the need to edit MP3 files in this way I encourage you to check out the application.

    The image “Speaker” was uploaded to the stock.xchng website by Brian Lary and found using the everystockphoto search engine.

    Posted in Linux, Musings. Tags: , , . No Comments »

    Sunset at Brighton Jetty

    A couple of weekends ago we went down to to the Brighton Jetty on a cold and windy afternoon and the sunset was just amazing. These photos don’t do it justice.


    (Click image for larger version)


    (Click image for larger version)

    Only on Windows…

    … could a progress dialog box for a software installer claim it had over 8,000 years to go before the installation was finished. Personally, that was much longer than I was prepared to wait.

    A screen capture of a progress dialog window

    The title of the program has been obscured, to protect the guilty… er… innocent.

    Waves crashing on the beach

    Waves crashing on the beach near the Brighton Jetty


    (Click image for larger version)


    (Click image for larger version)