AmCharts-PHP Class Library

Filed under: AmCharts-PHP,Web-Development — Matthias Burtscher @ 19. February 2009 09:28 | Comments (45)

Sample Chart with AmChartsA few weeks ago I had the pleasure to integrate the very nice AmCharts into one of our products. After a few tests in general (my colleague Stefan wrote about it – German) we decided to build a PHP5 library around the AmCharts Flash objects to create and configure charts in a more convenient way.

Usual integration

You usually configure AmCharts using one or more XML files (one for the settings and one for the data in most cases). This is great if you have static data and constant settings. We use AmCharts to create charts with data retrieved from a database. We could now use a PHP script to create the XML file AmCharts use. Our settings also vary from chart to chart. So we also need a settings file for each different chart. IMHO that’s too much code for a few charts, so we had to find another way to create them.

The solution

AmCharts offers the possibility to pass all settings and data via flash variables instead of external XML files. And that’s what we use in our Library. All parameters (chart type, settings, data) are passed via flash variables. That generates a lot of inline HTML code but eliminates a lot of files and headache when managing the source.

Because writing the XML strings for settings and data is not as easy as it should be we had to create a few classes to generate the ready-to-use HTML code directly in PHP.

An example

This example shows how to create a simple pie chart with two slices once in the plain old style and once using AmCharts-PHP.

Using XML files

settings.xml

  1. <settings>
  2.   <pie>
  3.     <angle>45</angle>
  4.     <height>10</height>
  5.   </pie>
  6. </settings>

data.xml

  1. <pie>
  2.   <slice title="Democrats (Obama)" color="#0000FF" pull_out="true">365</slice>
  3.   <slice title="Republicans (McCain)" color="#FF0000">173</slice>
  4. </pie>

Website integration

  1. <script type="text/javascript" src="amline/swfobject.js"></script>
  2. <div id="flashcontent">
  3.   <strong>You need to upgrade your Flash Player</strong>
  4. </div>
  5. <script type="text/javascript">
  6. // <![CDATA[       
  7. var so = new SWFObject("amline/ampie.swf", "ampie", "520", "400", "8", "#FFFFFF");
  8. so.addVariable("path", "ampie/");
  9. so.addVariable("settings_file", escape("settings.xml"));
  10. so.addVariable("data_file", escape("data.xml"));
  11. so.write("flashcontent");
  12. // ]]>
  13. </script>

Using AmCharts-PHP

  1. $chart = new AmPieChart("election2008");
  2. $chart->setConfig("pie.angle", 45);
  3. $chart->setConfig("pie.height", 10);
  4. $chart->addSlice("democrats", "Democrats (Barack Obama)", 365,
  5.   array("color" => "#0000FF", "pull_out" => "true"));
  6. $chart->addSlice("republicans", "Republicans (John McCain)", 173,
  7.   array("color" => "#FF0000"));
  8. echo $chart->getCode();

As we see, it’s much more comfortable to use and much more flexible.

Licencing

AmCharts-PHP is published under the GNU Lesser General Public Licence.

Download

You can download AmCharts-PHP from Sourceforge.

Tags: ,

45 Comments »

  1. Comment by Alexandre Paulo — 26. February 2009 @ 11:33

    The swfobjects.js file on your examples and the one downloaded from amcharts are different and incompatible?

    If I use the one donwloade from amcharts I get “chart loadling” and the chart never gets displayed…

  2. Comment by Matthias Burtscher — 26. February 2009 @ 12:18

    The one delivered with AmCharts-PHP is a newer version which works differently. If you use AmCharts-PHP you have to use the newer version (2.0).

  3. Comment by Alexandre Paulo — 26. February 2009 @ 12:38

    Where can I get the new version of AmCharts-PHP?… Sourceforge only has 0.1.0…

  4. Comment by Matthias Burtscher — 26. February 2009 @ 13:03

    The swfobject.js from the AmCharts-PHP 0.1.0 bundle is version 2.0. You find it in the examples folder.

  5. Comment by Alexandre Paulo — 26. February 2009 @ 13:08

    Ok… That’s the one I’ve got.
    Do you have a user guide on this? I am taking to long just do understand on how to config the graphs…

    How do we set the chart width and height?
    How does SetConfig works?

    Thanks a lot

  6. Comment by Matthias Burtscher — 26. February 2009 @ 13:26

    There will be a more detailed example on chart configuration in the next release. Until then, this is a “real-life” example from one of our products:

    AmChart::$jsPath = “tools/amcharts-php/AmCharts.js”;
    AmChart::$libraryPath = “tools/amcharts”;
    AmChart::$swfObjectPath = “tools/swfobject/swfobject.js”;

    $chart = new AmLineChart(“test”);

    // Sets chart config
    $chart->setConfigAll(array(
    “width” => “100%”,
    “height” => 300,
    “plot_area.margins.left” => 80,
    “plot_area.margins.right” => 10,
    “plot_area.margins.top” => 10,
    “grid.x.enabled” => false,
    “grid.x.approx_count” => 10,
    “grid.y_left.enabled” => true,
    “grid.y_right.enabled” => false,
    “values.x.enabled” => true,
    “values.x.rotate” => 90,
    “values.x.skip_first” => false,
    “values.x.skip_last” => false,
    “values.y_left.enabled” => true,
    “values.y_left.reverse” => false,
    “values.y_left.frequency” => 1,
    “values.y_right.enabled” => false,
    “values.y_right.reverse” => false,
    “values.y_right.frequency” => 2,
    “axes.x.width” => 1,
    “axes.y_left.width” => 1,
    “axes.y_right.width” => 1,
    “indicator.enabled” => true,
    “indicator.zoomable” => true,
    “indicator.x_balloon_enabled” => true
    ));

    // Sets default config for graphs (lines in a line chart)
    $chart->setDefaultGraphConfig(array(
    “hidden” => false,
    “bullet” => “round_outlined”,
    “bullet_size” => 12,
    “line_width” => 4
    ));

    You can find all available settings in the official AmCharts-documentation.

  7. Comment by Instant Leads — 9. March 2009 @ 00:59

    I am looking to use this software to display data with my current PHP/Mysql software, but am not a programmer, if anyone has experience with doing this then i would appreciate them contacting me. My name is Simon and i can be contacted at sales@instant-leads.com

  8. Comment by bobby — 11. March 2009 @ 09:30

    report bug
    AmChart.php
    line 191
    public function setLibraryPath($_path) {
    $this->libraryPath = $_path; //—>self::$libraryPath = $_path;
    }

  9. Comment by Matthias Burtscher — 11. March 2009 @ 09:47

    Fixed for the next release. I didn’t realize that because the function setLibraryPath is obsolete. the $libraryPath member is public.

  10. Comment by Steven Fransen — 14. March 2009 @ 02:01

    I can’t make this work with Safari I have tried many times and It does work Works with other browsers on mac Just not Safari. Any Ideas

  11. Comment by Matthias Burtscher — 17. March 2009 @ 14:01

    I have no problems using Safari 3.2.1. Which version of Safari do you use?

  12. Comment by maz — 17. March 2009 @ 18:38

    Nice. Unless I am mistaken, there is no way to have two Y axes (line charts) at the moment. Is this something you are planning on adding?

  13. Comment by Matthias Burtscher — 18. March 2009 @ 07:50

    Using two Y axis is possible. Just use the settings from the AmCharts Documentation for AmCharts-PHP:
    $amLineChart->addGraph(“myId”, “Description of Graph”, $dataArray, array(“axis” => “right”));
    You can set the settings of the axis like this:
    $amLineChart->setConfig(“values.y_right.enabled”, true);

  14. Comment by maz — 23. March 2009 @ 05:43

    Nice. Thanks!

  15. Comment by Steven Fransen — 23. March 2009 @ 09:56

    I found the problem with safari I am using both 3.2.1 and 4.0 beta
    The problem is in line 104 of swfobject.js
    if(!(a.ie&&a.win)&&typeof g.createTextNode!=Z){k.appendChild(g.createTextNode(m+”{“+j+”}”))}l.appendChild(k);

    I is undefined
    If I remove the l.appendChild(k); from the code it works in all browser.
    I hope that help you out.
    I will comment out that line on my end.
    Thanks for the great tool.

  16. Comment by Alan — 3. May 2009 @ 16:54

    Ciao, I\’ve tried to use javacript to control the amcharts via your library but it seems that there are something that I dodn\’t completly understand.
    May you please post an example of how to control a chart?
    while amGetZoom function works well, the \’showall\’ and all the others to set the graph don\’t work.
    Seems that I can get the information from the graph but not set it.
    Ciao, ciao

  17. Comment by Steven Fransen — 15. May 2009 @ 01:15

    What I do is recreate the chart with the option of
    $HideAll = $_POST['HideAll'];
    if ( $HideAll == true)
    $theseHide = false; // Hide them all
    else
    $theseHide = true;// Show them all
    $chart->setDefaultGraphConfig(array(
    “hidden” => $theseHide,
    “bullet” => “round”, //_outlined
    “bullet_size” => 10,
    “line_width” => 2
    ));

    This was so much faster then trying to hide one at a time.
    It time a spilt second to recreate the table again.
    I Hope this helps.
    if you need more code to help just say so. I used a drop down menu to control this feature.

    Steven

  18. Comment by ap — 15. May 2009 @ 11:43

    how to enable labels?
    I tried:
    $chart->setConfig(“data_labels.show”, “”);
    but it converts to html symbols so that it won’t work…

  19. Comment by ap — 15. May 2009 @ 11:48

    my last comment was altered, i’ll try html codes…
    $chart->setConfig(“data_labels.show”, “<![CDATA[{title}: {percents}%]]>”);
    anyway, the config value is inside “less than” and “greater than” symbols.

  20. Comment by Rahul — 24. May 2009 @ 03:34

    Just a warning: This doesn’t seem to work in Chrome. I spent quite a bit of time trying to make it work before i thought of testing in another browser. Chrome will say “Chart is loading” but it never loads. Works fine in FF and IE.

  21. Comment by Rahul — 24. May 2009 @ 07:12

    Would appreciate it if somebody could show me how to pass data from a database to the PHP file to display a stacked bar chart? All data, including balloon text is stored in the database. Its all right if the colours of the bar are hard-coded before hand

  22. Comment by Dan — 26. May 2009 @ 11:47

    I’ve followed recommendations and setup here to the letter, but I can’t get this to 1) have more than one graph in a page (tried $chart2 on everything etc. as alternatives) and 2) get the config to actually do what I ask.

    It parses the code correctly into the page, but config options such as animate etc. don’t materialise. Though width and basic adjustments do, so it is ‘getting through’. Am I the only one finding this all a bit more difficult than it should be?

  23. Comment by Steven Fransen — 26. May 2009 @ 22:41

    I have no problem have many charts on a Page.
    Just Change the $TableNum is it not the Same
    // Initialize the chart (the parameter is just a unique id used to handle multiple charts on one page.)
    $chart = new AmLineChart(“myLineChart_” . $TableNum);

    If you need more Help I can post a Full Example if needed.

  24. Comment by Steven Fransen — 26. May 2009 @ 22:44

    No Flash anything works in Chrome It is not just this code.

  25. Comment by Steven Fransen — 26. May 2009 @ 23:37

    If you get the swfobject.js swfobject_2_2_beta1.zip It fixes the problems with not loading the charts in safari.
    It will not work with the swfobject.js 2.1 version that is supplied in this download from here.

    I have no idea what bugs are in this beta but at least I can have charts again in Safari.

  26. Comment by broncha — 28. May 2009 @ 23:01

    Thanks for the effort to write this class.One thing I needed to know, how do you define settings for a particular slice through $chart->addSlice() ? I need to add a slice with following equivalent XML.
    17.819

  27. Comment by broncha — 28. May 2009 @ 23:02

    I am sorry .I think the html was filtered in last comment. here is the XML.
    slice title=”South America” pull_out=”true” color=”#FCD202″

  28. Comment by Matthias Burtscher — 29. May 2009 @ 06:54

    Just add the slice with the following parameters:
    $chart->addSlice(‘south_america’, ‘South America’, 10, array(‘pull_out’ => true, ‘color’ => ‘#FCD202′));
    The fourth parameter is a config array for the slice.

  29. Comment by broncha — 30. May 2009 @ 22:56

    Worked !! Thanks a lot.

  30. Comment by Cristian Veronesi — 23. June 2009 @ 15:23

    Hello, I would like to suggest a little improvement: in SWFObject 2.2 the embedSWF function has a 10th parameter that can be used to specify a callback function that is called on both success or failure of embedding a SWF file. You can use this parameter to display a message in case of Flash Player problems this way:

    $code .= \’\’
    . \’<div class=\"amChartInner\" …

    . \’swfobject.embedSWF(\"\’ . $this->getSwfPath() . \’\", \"chart_\’ . $this->id . \’_flash\", \"\’ . $width . \’\", \"\’ . $height . \’\", \"8\", \"\", flashvars, params, {}, function(event){if (!event.success) document.getElementById(\"chart_\’.$this->id.\’_flash\").innerHTML=\"Flash player error!\";} );\’ . \"\\n\"

  31. Comment by David Beuze — 20. July 2009 @ 15:24

    Hi, nice tools.

    For those who needs the library path to be passed over to the actual chart, add this to the getCode() function:

    . ‘flashvars.path = “‘ . self::$libraryPath . ‘”;’ . “\n”

    Maybe add this for next release?

  32. Comment by Sam — 20. July 2009 @ 22:37

    Hi, try to use the php code.
    How to make this work with Chrome?
    IE is OK, but in Chrome it just show : charts loading..

  33. Comment by Sam — 21. July 2009 @ 20:52

    Hi,,report
    went to google and downloaded the latet version of the swfobject.js (2.2), then chrome work!

    By the way, can anyone tell me where should I put the license key into (folder) ??

  34. Comment by David Beuze — 22. July 2009 @ 13:27

    Hi Sam,

    this was what my comment was referring to.

    Your license key file must be in the same folder as your .swf files (amcolumn.swf, amline.swf, …). But for your flash files to read the file, they must know it’s path.

    So the getCode() function becomes:
    …..
    . ‘// id . ‘”;’ . “\n”
    . ‘flashvars.chart_settings = escape(“‘ . str_replace(“\”", “‘”, $this->getConfigXml()) . ‘”);’ . \n”
    …..

    I guess you could put the file somewhere else as long as the path flashvars directs to that location, but I haven’t tried, and don’t know if there would be any side-effects.

  35. Comment by David Beuze — 22. July 2009 @ 13:29

    Edit: the code I posted above did not go through, take no notice of it, just add the line i posted further above.

    PS: at least your anti-code-injection mechanism seems to work :)

  36. Comment by Stephan — 29. July 2009 @ 17:15

    I\’ve wondered why I couldn\’t get the x-axis labels rotated by 45°.
    The reason is that the path to the \"fonts\" directory isn\’t referenced correctly:

    The Javascript variable \"path\" is missing. I added the following line in AmChart.php after line 127:

    . \’flashvars.path = \"\’ . self::$libraryPath . \’/\";\’ . \"\\n\"

  37. Comment by Stephan — 4. August 2009 @ 11:18

    Using “export.php” for exporting a chart as an PNG image doesn’t work – function “imagepng” must be called like this: imagepng($imgResource, NULL, 0, NULL);

    So in “export.php” it becomes: if ($imgtype == “png”) $function($img, NULL, 0, NULL);

  38. Comment by hans — 14. September 2009 @ 11:44

    Hi, Very nice library!
    Im trying to generate a stacked line graph. Is this possible with current version?
    Can you provide a detailed example?
    Thanks in advance

  39. Comment by Haynes — 27. September 2009 @ 18:52

    Very nice library. Is google the best place to get the 2.2 version of swfobject?

  40. Comment by Pincl — 29. September 2009 @ 13:15

    Great library compared to others but is it possible to use multiple labels on a chart?! Ive been tryng it for two days now and im beginning to suspect its impssible to configure using PHP. Am i the only one whos having this problem? Here is my code, can anybody help?

    $chart->setConfigAll(array(
    “labels.label.x” => 0,
    “labels.label.y” => 20,
    “labels.label.text” => “cells   ml“,
    ));
    how can i add another label into x- 100, y – 20

  41. Comment by Pincl — 29. September 2009 @ 13:27

    found it, anybody having this kind of newbie problems described above use:
    $myChart->addLabel(“blah”, 0, 20 );

  42. Comment by Fabrice — 6. March 2010 @ 08:35

    I’m trying to integrate amcharts-php on a wordpress site.
    I think it would be great if the user can add the scripts links into the header of the html page (through the wordpress functions).
    For that, I added a parameter to the constructor to specify if amcharts-php shall include the script links or not.
    Regards.

  43. Comment by wratke — 16. June 2010 @ 05:42

    This is a really great library, thanks a lot for throwing it together. I did have one problem with the array2xml method in AmChart.php spitting out funky xml on a live server (I had no problem with it locally using wamp). I finally traced the problem down to line 278 ‘if($nextNode == null){‘. The $nextNode was being caught as null when it shouldn’t have been which was causing multiple nodes to be generated when there only should have been one. I changed it to ‘if($nextNode === null){‘ so that it makes sure that the comparison is strongly typed and now everything is working fine.

    Cheers.

  44. Comment by Ignacio Mella — 22. July 2010 @ 19:52

    Excellent library!. Thanks for sharing.

  45. Comment by Ignacio Mella — 22. July 2010 @ 20:14

    Mmm… From what I see ( I think there should be a addGuide function.

Leave a comment