Composing JSON object for Google Chart API in PHP

This example from google document for using server side code uses the ready to use JSON data.
Here is the example of using PHP to compose the same JSON data as the JSON data from Google’s example.

1. The exampleUsingPHP.html, this file will be the exact same as from the Google’s example.

    <!--Load the AJAX API-->
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="//"></script>
    <script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});
    // Set a callback to run when the Google Visualization API is loaded.
    function drawChart() {
      var jsonData = $.ajax({
          url: "getData.php",
          async: false
      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});


    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>

2. The getData.php file, this will be the different from Google’s example. Instead of getting the ready to use JSON data from a file, we will compose the JSON data using PHP. It’s hard coded so it will create the same JSON data as the one provided from Google’s document, but you can change it to get the data from a database.

// All to values below are hard coded to match the data provide from Google's document.
// You can always customize it to use the data from a databbase.
// If you use the data from a database, using a loop to create the values for cols and rows
// will be a good choice.
$cols = array($col1,$col2);








echo json_encode($data);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search