Click here to Skip to main content
15,867,895 members
Articles / Web Development / HTML

Creating Interactive HTML5 Graphs in PHP

Rate me:
Please Sign up or sign in to vote.
4.87/5 (14 votes)
15 May 2014CPOL6 min read 97.7K   7   30   3
Achieve professional-level web-based charts in PHP without in-depth knowledge of HTML5 or JavaScript.

Introduction

Recently, I had the need to quickly create graphs from a set of PHP data arrays. The requirements are the graphs must be interactive, user-friendly, and also downloadable. After evaluating a number of PHP graph solutions including phpChart, pChart, and Highcharts, I decided to use phpChart as my tool of choice. This article is about my experience with phpChart.

Background

Being a mainly back-end programmer, I don’t have time for hours of hard work with JavaScript (client wanted the charts be available online in 24 hours), neither possess the knowledge of advanced front-end coding. Basically, I want something allowing PHP developers with hardly any front-end programming experience to quickly develop great-looking graphs.

I’ve tried pChart, a popular PHP chart library. The generated graphs look decent, though downloadable, but the graphs are all static images... that's so 90’s. Highcharts seems like the best alternative. The graphs look amazing, animated, and tons of customizing options, but at the same time, it is extremely complex, and require a great amount of JavaScript knowledge. Highcharts is neither PHP specific is nor free for commercial use.

phpChart Basic

What I like the most about the phpChart how easy and minimums amount of code to get started. It’s hard to overstate how much simpler front-end programming becomes to develop a basic PHP graphs, the best way to illustrate is with an example.

phpChart Lite can be downloaded here http://phpchart.org/downloads/. Download the file and extract to web root.

Setup conf.php

The first thing is to set the variable SCRIPTPATH to the PhpChart class library in conf.php file. The variable represents the relative or absolute URL to phpChart library on your web server.

PHP
define('SCRIPTPATH','/phpChart/');   

Creating the Simplest Graph

Include conf.php at the beginning of your PHP file:

PHP
require_once("../conf.php");

Call the constructor C_PhpChartX, the finally call the draw() function.

PHP
$pc=new C_PhpChartX(array(array(123, 34, 51, 22, 3)), ‘simplest_graph’);
$pc->draw();  

That’s all the code you need to get started. Here’s the rendered output.

Image 1

That’s what I called minimum coding. When you get a team of coders working on something, it just doesn’t make sense to have them learning to do the basics the hard way. The last thing any programmer wants to do is to slog through convoluted documentation for a new set of libraries or tools.

A side note, the second parameter in the constructor should be a unique name to your graph. Here I entered “simplest_graph”, but it could be any non-space string. It must be an unique value because you could have multiple charts in a page (I’m using phpChart Enterprise, the free Lite version restrict to one chart per page, just let you know).

Adding a Title

You should add title to your chart so your users know what they are looking at

PHP
$pc->set_title(array('text'=>’My Simplest Graph')); 

Adding Animation

One of the things pChart could not do is animation. In phpChart, animation is supported out of box by simply calling set_animate and pass true value.

PHP
$pc->set_animate(true);  

That’s it. Your chart should now have a title and is animated when rendered. Full code is displayed below:

PHP
$pc = new C_PhpChartX(array(array(123, 34, 51, 22, 3)),'simplest_graph');
$pc->set_animate(true);
$pc->set_title(array('text'=>'My Simplest Graph'));
$pc->draw();   

Under the Hood

If you view the source in your browser, you will notice that phpChart automatically include a number of JavaScript as well as CSS files including jquery.js, jquery-ui, and jqplot.js, jquery-ui.css etc. The graphs are rendered in your browser by JavaScript on the client side, but the code is entirely in PHP on the front-end.

What’s cool about this is that me as a PHP developers don’t need to worry about JavaScript because phpChart automatically handle that for me. Below is the entire generated JavaScript code in the view source as a result of my four lines of PHP code illustrated earlier.

HTML
<script language="JavaScript" type="text/javascript"> 
     var _simplest_graph_plot_properties;
    $(document).ready(function(){ 
    setTimeout( function() { 
    _simplest_graph_plot_properties = {
    "title":{
    "text":"My Simplest Graph","show":1
    },"animate":true,"animateReplot":true
    }
    
    $.jqplot.config.enablePlugins = true;
    $.jqplot.config.defaultHeight = 300;
    $.jqplot.config.defaultWidth = 400;
    _simplest_graph= $.jqplot("simplest_graph", 
           [[123, 34, 51, 22, 3]], _simplest_graph_plot_properties);
    
    }, 200 );
    });
</script>

As you may also notice, “simplest_graph” is used as a part of a JavaScript variable as _simplest_graph_plot_properties representing the jqplot object. This is the reason why the name must be unique.

In additional, the PHP data array is automatically converted to JavaScript array, so below PHP array:

PHP
array(array(123, 34, 51, 22, 3)) 

becomes JavaScript array:

JavaScript
[[123,34,51,22,3]]

Change Renderer Type

PhpChart provides support for implementations of bar, line, and stack charts; banded line graphs; block plots; bubble charts; candlestick graphs; gecko charts; meter graphs; and several other types of plots. A list of renderers supported:

  • BarRenderer
  • BezierCurveRenderer
  • BlockRenderer
  • BubbleRenderer
  • CanvasAxisLabelRenderer
  • CanvasAxisTickRenderer
  • CategoryAxisRenderer
  • DateAxisRenderer
  • DonutRenderer
  • EnhancedLegendRenderer
  • FunnelRenderer
  • LogAxisRenderer
  • MekkoAxisRenderer
  • MekkoRenderer
  • MeterGaugeRenderer
  • OHLCRenderer
  • PyramidAxisRenderer
  • PieRenderer

Source: http://phpchart.org/examples/change-renderer-type/

The default chart type is line chart if the type is not specified. To change the chart type, call set_series_default function. e.g., change the above example to pie chart

PHP
$pc->set_series_default(array('renderer'=>'plugin::PieRenderer')); 

Image 2

Please note that I'm using phpChart Enterprise. phpChart Lite supports only line chart.

Array and Naming Convention

Something worth to take note here. First of all, almost all the parameters used in phpChart functions are an array, not all, but almost all of them are. Just keep that in mind. It will save you a lot of headache when debugging (I will cover briefly the debugging feature later). Secondly, a renderer is actually called a “plugin” in phpChart and you must pass it like this “plugin::PieRenderer”, with double colons in between. For custom JavaScript, use “js::yourJavascriptFunctioName”.

Advanced phpChart: Custom JavaScript

So far all I'm showing you are in PHP. In most cases, phpChart will do fine with simple PHP function calls. To take the full advantage of phpChart you will like to use custom javascript. For example, you can have phpChart to load data from from a JavaScript function or an external source.

Below sineRenderer is a custom JavaScript function defined to display sine value from a set of random numbers. It's passed to set_data_renderer function.

PHP:

PHP
$data1 = array();
$pc = new C_PhpChartX(array($data1),'basic_chart_4');
$pc->set_title(array('text'=>'Basic Chart with Custom JS'));
$pc->set_data_renderer("js::sineRenderer");
$pc->add_plugins(array('pointLabels'));
$pc->set_animate(true);
$pc->draw(); 

JavaScript:

JavaScript
sineRenderer = function() {
    var data = [[]];
    for (var i=0; i<13; i+=0.5) {
      data[0].push([i, Math.sin(i)]);
    }
    return data;
  };  

More about set_data_renderer function can be found here: http://phpchart.org/phpChart/docs/output/C_PhpChartX_set_data_renderer@.html

Image 3

Export Charts to Images

This puzzled me a little in the beginning because I couldn't figure out how to export the charts. It turns out that phpChart can export charts to downloadable images but the procedure is not well documented. I’ve found add the following to the BOTTOM of all the page, does the trick:

HTML
<script type="text/javascript" 
  src="http://www.codeproject.com/phpChart/js/showjs.js"></script> 

Download showjs.js: http://phpchart.org/phpChart/js/showjs.js

Debug phpChart

Last, before I wrap up, I should mention one invaluable feature of phpChart. That is it’s build-in debug feature. On its website, all of its online examples (http://phpchart.org/examples/) have the debug enabled with live demo and two tabs of clear, easily portable code underneath -- JavaScript and PHP, respectively.

To enable debug, simply add the following line to conf.php file:

PHP
define('DEBUG', true);  

Image 4

Final Thoughts

One of the main benefits of PhpChart is that by using this tool, PHP programmers can achieve professional-level web-based charts -- without having in-depth knowledge of HTML5 or JavaScript.

If you’re like me who are new to front-end programming and you need to generate interactive web charts, you will probably like phpChart. A full list of phpChart examples of HTML5 graphs are list on one single page below. With any luck, you’ll hardly need the documentation -- instead you’ll get right to the code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
He likes programming and iPod.

Comments and Discussions

 
QuestionProblem in output Pin
Member 1119606131-Oct-14 4:48
Member 1119606131-Oct-14 4:48 
GeneralMy vote of 5 Pin
Anurag Gandhi12-Jun-13 3:50
professionalAnurag Gandhi12-Jun-13 3:50 
GeneralMy vote of 5 Pin
ursixc910-Jun-13 1:48
ursixc910-Jun-13 1:48 
Very useful and informative.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.