Dynamically Creating Graphs and Charts with PHP and GDChart

Sep 23, 2008 Author: vvaswani

Friday Night Fever If you've been working with PHP for a while, you already know that the language makes dynamic image generation very simple: the GD extension and a few lines of PHP code are all you need to create a JPEG, GIF or PNG image from scratch. However, while this works remarkably well for simple tasks, it can become tedious and complicated if you need to generate more complex images, such as graphs and charts, at run-time. Take, for example, the task of turning a set of data values into a pie chart image. To arrive at the required result, you would need to allocate colors for each slice of the pie, calculate arc endpoints corresponding to the slice sizes, draw arcs and lines, fill each slice with a different color, write a descriptive text string and percentage value next to each slice, and render the final image. Completing the task might require between 80-100 lines of code and a few hours of debugging time...definitely not the most fun way to spend a Friday evening! However, there's a simpler alternative: PHP's GDChart extension, which provides a full-featured API to efficiently generate charts and graphs. This extension, which is freely available from PECL, can significantly reduce the amount of work involved in dynamically generating graphical representations of numerical data at run-time. Over the next few pages, I'll introduce you to this extension, illustrating its important features and showing you just how easy it is to get your Friday evening back. Putting The Pieces Together GDChart support in PHP comes through PECL's ext/gdchart extension, which is maintained by Ilia Alshanetsky and Rasmus Lerdorf, and provides an object-oriented API for chart generation. This ext/gdchart extension, in turn, requires you to have GD support compiled into your PHP build. On UNIX systems, this is accomplished by downloading and installing the GD libraries from http://www.boutell.com/gd/ (if you don't already have them), and then compiling PHP with the --with-gd configuration directive. Once this is done, you can proceed to install the GDChart extension using the pecl command. Note that at the current time, a Windows version of ext/gdchart is not available; the following steps assume a *NIX system.

Read More

views 7884
  1. Add New Comment