How to Graph in PHP
The PHP GD extension is useful for creating and manipulating images, but it would be too difficult to use that extension to generate graphs and charts. To graph in PHP, you can use the PHP GDChart extension, which is available through the PHP Extension Community Library (PECL). After installing the GDChart extension using PECL, you can use the methods associated with the GDChart object to create graphs and charts.
Instructions
-
-
1
Open a command line on the Web server and install the GD Chart extension as the superuser through PECL. For example, type:
sudo pecl install gdchart-beta
Enter the password when prompted.
-
2
Create a new PHP file to graph mean earnings by educational level achieved for 2008 from the U.S. Census. Add the HTML headers to the file. For example, type:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Education and Income</title>
</head>
<body>
-
-
3
Add a new GDChart bar chart object. For example, type:
<?php
$chart = new GDChart(GDChart::BAR);
-
4
Add the data values to the chart object using the "addValues" method. For example, type:
$chart->addValues(array(21023, 31283, 32555, 39506, 58613, 70856, 125019, 99697));
-
5
Add the labels for the data values to the chart object using the "setLabels" method. For example, type:
$chart->setLabels(array("No HS", "HS Degree", "College No Degree", "Associate's", "Bachelor's", "Master's", "Professional", "Doctorate"));
-
6
Set the header so HTML understands you are displaying the chart as a PNG image. For example, type:
header("Content-Type:image/png");
-
7
Display the chart as a PNG image using the "out" method. For example, type:
echo $chart->out(300, 200, GDChart::PNG);
?>
</body>
</html>
-
1
Tips & Warnings
You must have administrator access to your Web server in order to install the GDChart extension. If you don't have administrator access, ask your Web hosting provider to install the extension for you.
References
Resources
- Photo Credit Hemera Technologies/Photos.com/Getty Images