How can PHP be used to create a graphical representation of temperature trends over time?
To create a graphical representation of temperature trends over time using PHP, we can utilize a charting library like Google Charts or Chart.js. We can fetch temperature data from a database or an API, format it appropriately, and then pass it to the charting library to generate the graph.
<?php
// Sample temperature data
$temperatures = [
['Date', 'Temperature'],
['2022-01-01', 25],
['2022-01-02', 28],
['2022-01-03', 30],
['2022-01-04', 26],
['2022-01-05', 29],
];
// Convert temperature data to JSON format
$temperatureJson = json_encode($temperatures);
?>
<!DOCTYPE html>
<html>
<head>
<title>Temperature Trends</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $temperatureJson; ?>);
var options = {
title: 'Temperature Trends',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Keywords
Related Questions
- What is the function mysql_insert_id() in PHP and how can it be used to retrieve the ID of a newly inserted database entry?
- How does the Facade pattern in Laravel work, and what benefits does it offer in terms of code organization and flexibility?
- What are the potential pitfalls of accessing POST data in PHP?