架構說明
- 前端 Highcharts 載入
<script src="https://code.highcharts.com/highcharts.js">
- AJAX 請求 PHP API 取得 JSON 資料
- PHP 查詢資料庫 → 陣列 →
json_encode() 輸出
- Highcharts
series 直接使用 JSON 陣列
後端 PHP (chart_data.php)
<?php
header('Content-Type: application/json; charset=utf-8');
$pdo = new PDO("mysql:host=localhost;dbname=stats;charset=utf8", 'user', 'pass');
// 範例:各城市銷售額
$stmt = $pdo->query("SELECT city, SUM(amount) as total FROM orders GROUP BY city ORDER BY total DESC");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Highcharts 需要格式:[['城市', 數值], ...] 或 [{name:'城市', y:數值}, ...]
$data = [];
foreach ($rows as $r) {
$data[] = ['name' => $r['city'], 'y' => (float)$r['total']];
}
// 可選:前端指定 sliced/selected
// $data[2]['sliced'] = $data[2]['selected'] = true;
echo json_encode($data);
前端 HTML + JavaScript
<div id="chart" style="width:100%; height:400px"></div>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script>
fetch('chart_data.php')
.then(r => r.json())
.then(data => {
Highcharts.chart('chart', {
chart: { type: 'pie' },
title: { text: '各城市銷售佔比' },
tooltip: { pointFormat: '{series.name}: {point.percentage:.1f}%' },
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: { enabled: true, format: '{point.name}: {point.y:.0f}' }
}
},
series: [{
name: '銷售額',
colorByPoint: true,
data: data // 直接使用 JSON 陣列
}]
});
});
</script>
多系列圖表 (柱狀/折線混合)
<?php
// 後端回傳多系列
$series = [];
// 系列 1: 銷售額
$stmt = $pdo->query("SELECT month, SUM(amount) FROM orders GROUP BY month ORDER BY month");
$series[] = ['name'=>'銷售額', 'type'=>'column', 'data'=>$stmt->fetchAll(PDO::FETCH_COLUMN, 1)];
// 系列 2: 訂單量
$stmt = $pdo->query("SELECT month, COUNT(*) FROM orders GROUP BY month ORDER BY month");
$series[] = ['name'=>'訂單量', 'type'=>'spline', 'yAxis'=>1, 'data'=>$stmt->fetchAll(PDO::FETCH_COLUMN, 1)];
echo json_encode($series);
?>
// 前端
fetch('chart_data.php').then(r=>r.json()).then(series => {
Highcharts.chart('chart', {
chart: { type: 'column' },
yAxis: [{ title:{text:'金額'} }, { title:{text:'筆數'}, opposite:true }],
series: series
});
});
即時更新 (WebSocket / 輪詢)
function loadChart() {
fetch('chart_data.php').then(r=>r.json()).then(data => {
chart.series[0].setData(data, true); // 重繪
});
}
setInterval(loadChart, 30000); // 每 30 秒更新
大數據量優化
- 啟用
boost.js 模組 (<script src="https://code.highcharts.com/modules/boost.js">)
- 資料抽樣/聚合在 SQL 層完成 (
GROUP BY、TIME_BUCKET)
- 前端
dataGrouping 自動聚合
- 考慮
Highcharts Stock 專為時間序列大數據設計
匯出功能
// 匯出按鈕
button.onclick = () => chart.downloadImage('image/png', {filename:'sales-chart'});
// 或匯出 PDF (需匯出模組)
chart.exportChart({type:'application/pdf', filename:'report'});