How to properly integrate google chart with php?

Member

by jerad , in category: PHP General , 6 months ago

How to properly integrate google chart with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 2 months ago

@jerad 

To properly integrate Google Chart with PHP, you can follow the steps below:

  1. Include the Google Chart JavaScript library in your HTML file. You can add the following code in your HTML file:
1
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>


  1. Create a PHP file that will generate the data for the chart. This file will query your database or use any other method to retrieve the data and return it in JSON format. For example, you can create a file named data.php with the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
// Database connection code goes here

$data = array(
    array('Year', 'Sales', 'Expenses'),
    array('2010', 1000, 400),
    array('2011', 1170, 460),
    array('2012', 660, 1120),
    array('2013', 1030, 540)
);

echo json_encode($data);
?>


  1. Load the Google Chart API and draw the chart in your HTML file using the data returned from the PHP file. You can add the following code in your HTML file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var jsonData = $.ajax({
        url: "data.php",
        dataType: "json",
        async: false
    }).responseText;

    var data = new google.visualization.arrayToDataTable(JSON.parse(jsonData));

    var options = {
        title: 'Company Performance',
        curveType: 'function',
        legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}
</script>

<div id="chart_div" style="width: 900px; height: 500px;"></div>


  1. Make sure to include jQuery in your HTML file if you are using it for AJAX requests:
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>


  1. Finally, run your HTML file in a web browser to see the Google Chart displaying the data returned from the PHP file.


By following these steps, you can integrate Google Chart with PHP and display dynamic data in your charts.