jpgraph 汉字乱码解决方案及实例

原创
2016-06-13 10:38:01 699浏览

  JPGRAPH是PHP世界里一款非常方便的做各种图表的工作,柱状图、饼图、雷达图等,基本上对所有的图表无所不能。

  在PEAR中,也有一款做图表的工具,叫image_graph,这个工具功能也是非常强大,但jpgraph和image_graph比起来的最大好处,就是有很多的例子和非常详细的文档说明,这就使jpgraph用起来是相当的方便。

  最后决定选用jpgraph。

  下面是一段代码。同时在用的过程中遇到了汉字乱码的问题,原因已经找到,也和大家说明一下。

  如果您在使用jpgraph的过程遇到了什么问题,可以MAIL给我,大家一直探讨。同时,如果你有什么使用心得,也希望您能够发到LAMPER上,让更多的人分享你的经验。

  1. include ("../jpgraph.php"); 
  2. include ("../jpgraph_line.php"); 
  3.  
  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.  
  8. // Create the graph. These two calls are always required 
  9. $graph = new Graph(800,400,"auto");  
  10. $graph->img->SetMargin(40,40,20,40); 
  11.  
  12. $graph->title->SetFont(FF_SIMSUN,FS_BOLD); 
  13. $title = "展示pv/展示ip"; 
  14. $graph->title->Set($title); 
  15.  
  16. $graph->SetScale("textlin"); 
  17. $graph->SetY2Scale("lin"); 
  18.  
  19. $graph->xaxis->title->Set("时间"); 
  20. $graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD); 
  21. $graph->xaxis->SetTickLabels($datax); 
  22.  
  23. $graph->yaxis->title->Set("展示pv"); 
  24. $graph->yaxis->SetColor("blue"); 
  25. $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD); 
  26.  
  27. $graph->y2axis->title->Set("展示IP"); 
  28. $graph->y2axis->SetColor("orange"); 
  29. $graph->y2axis->title->SetFont(FF_SIMSUN,FS_BOLD); 
  30.  
  31. $lineplot=new LinePlot($ydata); 
  32. $lineplot->SetColor("blue"); 
  33. $lineplot->SetWeight(2); 
  34. $lineplot->SetLegend("展示pv"); 
  35. $graph->legend->SetFont(FF_SIMSUN,FS_BOLD); 
  36.  
  37. $lineplot2=new LinePlot($y2data); 
  38. $lineplot2->SetColor("orange"); 
  39. $lineplot2->SetWeight(2); 
  40. $lineplot2->SetLegend("展示ip"); 
  41.  
  42.  
  43. $graph->Add($lineplot); 
  44. $graph->AddY2($lineplot2); 
  45.  
  46. // Display the graph 
  47. $graph->Stroke(); 
  48. ?> 

  注意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,这样你的汉字才可以正常显示。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。