在前面的JpGraph使用詳解這篇文章,已經對JpGraph的使用方法作了詳細的交代,前面說好的,接下來解決中文亂碼。
JpGraph為什么會出現中文亂碼
在JpGraph中默認是要把字符串轉成utf8的,但是如果你的文件本身就是utf8的,並且要用中文字體,它還會轉一遍,結果多轉了一次,就會出現亂碼。如圖所示
解決中文亂碼
取前篇的代碼片斷如下
//設置圖表的標題字體、大小 $graph->title->Set("Accumulated bar plots"); $graph->xaxis->title->Set("X-title"); $graph->yaxis->title->Set("Y-title"); //和上面標題對應,設置標題的字體和大小 $graph->title->SetFont(FF_FONT1,FS_BOLD); $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD); $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
把它改為
//設置圖表的標題字體、大小 $graph->title->Set(iconv("UTF-8","GB2312//IGNORE","網志博客信息統計表")); $graph->xaxis->title->Set(iconv("UTF-8","GB2312//IGNORE","X-標題")); $graph->yaxis->title->Set(iconv("UTF-8","GB2312//IGNORE","Y-標題")); //和上面標題對應,設置標題的字體和大小 $graph->title->SetFont(FF_SIMSUN,FS_BOLD); $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD); $graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);
使用php函數據中文由UTF-8轉為GB2312,記住由於iconv本身的一個bug,iconv在轉換字符"—"到gb2312時會出錯,所以在需要轉成的編碼后加上 "//IGNORE" 。
FF_SIMSUN表示中文簡體,對應的字體文件是simsun.ttc,雖然FF_CHINESE和FF_BIG5也表示中文但是它們對應的字體文件是不同的,所以不要弄錯。
下面是正確轉換后生成的圖
下面是本例調試的完整代碼
require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_bar.php'); $data1y=array(0,8,9,3,5,6); $data2y=array(18,2,1,7,5,4); // Create the graph. These two calls are always required $graph = new Graph(500,400); $graph->SetScale("textlin"); $graph->SetShadow(); $graph->img->SetMargin(40,30,20,40);//設置圖形的邊距 // Create the bar plots $b1plot = new BarPlot($data1y); $b1plot->SetFillColor("orange"); $b1plot->value->Show(); $b2plot = new BarPlot($data2y); $b2plot->SetFillColor("blue"); $b2plot->value->Show(); // Create the grouped bar plot $gbplot = new AccBarPlot(array($b1plot,$b2plot)); // ...and add it to the graPH $graph->Add($gbplot); //設置標題字體樣式 $graph->title->Set(iconv("UTF-8","GB2312//IGNORE","網志博客信息統計表")); $graph->xaxis->title->Set(iconv("UTF-8","GB2312//IGNORE","X-標題")); $graph->yaxis->title->Set(iconv("UTF-8","GB2312//IGNORE","Y-標題")); $graph->title->SetFont(FF_SIMSUN,FS_BOLD); $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD); $graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD); $graph->Stroke();
當然了,我這里只介紹了一種方法,還有一種就是修改源碼,但不推薦。因為我覺得改動源碼可能會給其它地方帶來意想不到的麻煩。
使用JpGraph,要知道其版本、運行服務器以及操作系統的息息,不能張冠李戴,否則麻煩多多。
好了,至此JpGraph使用介紹也就這么多了。