1. 程式人生 > >jpgraph 漢字亂碼解決方案及例項

jpgraph 漢字亂碼解決方案及例項

JPGRAPH是PHP世界裡一款非常方便的做各種圖表的工作,柱狀圖、餅圖、雷達圖等,基本上對所有的圖表無所不能。

  在PEAR中,也有一款做圖表的工具,叫image_graph,這個工具功能也是非常強大,但jpgraph和image_graph比起來的最大好處,就是有很多的例子和非常詳細的文件說明,這就使jpgraph用起來是相當的方便。

  最後決定選用jpgraph。

  下面是一段程式碼。同時在用的過程中遇到了漢字亂碼的問題,原因已經找到,也和大家說明一下。

  如果您在使用jpgraph的過程遇到了什麼問題,可以MAIL給我,大家一直探討。同時,如果你有什麼使用心得,也希望您能夠發到LAMPER上,讓更多的人分享你的經驗。

  1. <?php   
  2. include ("../jpgraph.php");   
  3. include ("../jpgraph_line.php");   
  4. $ydata = array(11,3,8,12,5,1,9,13,5,7);   
  5. $y2data = array(354,200,265,99,111,91,198,225,293,251);   
  6. $datax = array("2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01","2006-01-01");   
  7. // Create the graph. These two calls are always required 
     
  8. $graph = new Graph(800,400,"auto");    
  9. $graph->img->SetMargin(40,40,20,40);   
  10. $graph->title->SetFont(FF_SIMSUN,FS_BOLD);   
  11. $title = "展示pv/展示ip";   
  12. $graph->title->Set($title);   
  13. $graph->SetScale("textlin");   
  14. $graph->SetY2Scale("lin");   
  15. $graph->xaxis->title->Set("時間");   
  16. $graph
    ->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);   
  17. $graph->xaxis->SetTickLabels($datax);   
  18. $graph->yaxis->title->Set("展示pv");   
  19. $graph->yaxis->SetColor("blue");   
  20. $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD);   
  21. $graph->y2axis->title->Set("展示IP");   
  22. $graph->y2axis->SetColor("orange");   
  23. $graph->y2axis->title->SetFont(FF_SIMSUN,FS_BOLD);   
  24. $lineplot=new LinePlot($ydata);   
  25. $lineplot->SetColor("blue");   
  26. $lineplot->SetWeight(2);   
  27. $lineplot->SetLegend("展示pv");   
  28. $graph->legend->SetFont(FF_SIMSUN,FS_BOLD);   
  29. $lineplot2=new LinePlot($y2data);   
  30. $lineplot2->SetColor("orange");   
  31. $lineplot2->SetWeight(2);   
  32. $lineplot2->SetLegend("展示ip");   
  33. $graph->Add($lineplot);   
  34. $graph->AddY2($lineplot2);   
  35. // Display the graph   
  36. $graph->Stroke();   
  37. ?>  

  注意SetFont方法,如果你的檔案編碼是gb2312,SetFont方法的第一個引數為FF_SIMSUN即可正常顯示漢字

  如果你的檔案編碼為utf-8,還需加一句$title = iconv("UTF-8", "gb2312", $title)

  在jpgraph.php中,有這麼一段語句:

elseif( $aFF === FF_SIMSUN ) {
   // Do Chinese conversion
   if( $this->g2312 == null ) {
 include_once 'jpgraph_gb2312.php' ;
 $this->g2312 = new GB2312toUTF8();
   }
   return $this->g2312->gb2utf8($aTxt);
}

  就是說,jpgraph預設顯示漢字時是把漢字編碼認為gb2312,轉化為utf-8以後再顯示。

  這樣的話,如果你的檔案編碼是gb2312,SetFont方法的第一個引數為FF_SIMSUN即可

  如果你是utf-8編碼你還需要先把漢字編碼轉化為gb2312,這樣你的漢字才可以正常顯示。