In modern web development, data visualization helps users understand trends and patterns more intuitively. By integrating a PHP API with the ECharts library, we can dynamically display backend data on the web in the form of statistical charts, achieving real-time data visualization.
Before you begin, make sure you have the following prepared:
The PHP API retrieves data from the database and returns it in JSON format to the frontend. Here’s a simple example:
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Database connection failed: " . $mysqli->connect_error);
}
// Query data
$query = "SELECT * FROM data_table";
$result = $mysqli->query($query);
// Convert results to JSON
$data = [];
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
// Return data as JSON
header('Content-Type: application/json');
echo json_encode($data);
// Close connection
$mysqli->close();
?>This PHP script connects to the database, retrieves records from the table, converts them into an array, and returns them as JSON data to the frontend.
The frontend uses Ajax to fetch data from the PHP API and ECharts to render the visualization dynamically.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP and ECharts Data Visualization Example</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
</head>
<body>
<div id="chart" style="width:800px;height:400px;"></div>
<script type="text/javascript">
$.ajax({
url: "api.php",
type: "GET",
dataType: "json",
success: function(data) {
var chart = echarts.init(document.getElementById('chart'));
var option = {
xAxis: {
type: 'category',
data: data.map(item => item.name)
},
yAxis: {
type: 'value'
},
series: [{
data: data.map(item => item.value),
type: 'bar'
}]
};
chart.setOption(option);
}
});
</script>
</body>
</html>This HTML page uses jQuery to request data from the PHP API, then initializes an ECharts instance to display the results as a bar chart, achieving real-time visualization.
It’s recommended to create a simple table in your database with two fields:
You can adjust the table structure and modify the SQL query as needed based on your project requirements.
By combining PHP APIs with the ECharts library, developers can efficiently implement data visualization features. The backend fetches data from a database, and the frontend dynamically renders it with ECharts to create interactive and visually appealing charts. This approach is ideal for dashboards, reports, and analytics in web applications.