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
- When should PHP developers use str_replace() instead of preg_replace() for string manipulation tasks?
- What are the potential pitfalls of using multiple SQL queries within a PHP script?
- What best practices should be followed when handling database queries in PHP to avoid errors like "Daten wurden geupdatet - betroffen war davon 0 Datensatz"?