使用PhpMyGraph从文件中绘制图形

时间:2014-07-17 08:16:31

标签: php file-io graph-drawing

在这些日子里,我正在尝试使用PhpMyGraph5.0从文件中绘制图形, 在autor的网站(http://phpmygraph.abisvmm.nl/)上有这个示例文件:

<?php    
//Set content-type header
header("Content-type: image/png");

//Include phpMyGraph5.0.php
include_once('phpMyGraph5.0.php');

//Set config directives
$cfg['title'] = 'Example graph';
$cfg['width'] = 500;
$cfg['height'] = 250;

//Set data
$data = array(
    'Jan' => 12,
    'Feb' => 25,
    'Mar' => 0,
    'Apr' => 7,
    'May' => 80,
    'Jun' => 67,
    'Jul' => 45,
    'Aug' => 66,
    'Sep' => 23,
    'Oct' => 23,
    'Nov' => 78,
    'Dec' => 23
);

//Create phpMyGraph instance
$graph = new phpMyGraph();

//Parse
$graph->parseHorizontalLineGraph($data, $cfg);
?> 

因为我需要从文件中获取输入,我修改了示例文件,改变了$ data赋值:

$data = file("$PATH/$MYFILE");

我已经在MYFILE中格式化了文本,这些是文件的一些行:

'00:00' => 19,
'00:05' => 19,
'00:10' => 21,
...
'17:10' => 21,
'17:15' => 21,
'17:20' => 21,

但是当我尝试绘制图形时,我获取此消息而不是图形:

"exception `Exception` with message `The value of the key %s` is not numeric.`"  

我在PhpMyGraph5.0.php中搜索过,我发现了抛出异常的测试:

//Loop
foreach($data as $key => $value) {
    //Test
    if(!is_numeric($value)) {
        throw new Exception('The value of the key "%s" is not numeric.');
    }
...

我试图用这个演员代替“抛出异常”:

$value=(int)$value;

但我只获得一张空图。

如果我手动将MYFILE的内容粘贴到$ data = array(PASTE_HERE)中;它有效,但我无法手动完成。

我认为问题是关于值的数据类型,但我对如何解决这个问题没有任何想法。

感谢大家,抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

该异常似乎编码错误,尝试将其更改为此并且它应该为您提供键的值,它发现值不是数字,这可能有助于识别错误的位置: -

throw new Exception(sprintf('The value of the key "%s" is not numeric.',$key));

修改

好的,我看到了问题,你没有从$data = file("$PATH/$MYFILE");

获得你认为的结果

如果您使用此

进行测试
$data = file("$PATH/$MYFILE");
print_r($data);

你得到了输出:

Array
(
    [0] => '00:00' => 19,
    [1] => '00:05' => 19,
    [2] => '00:10' => 21,
    [3] => '17:10' => 21,
    [4] => '17:15' => 21,
    [5] => '17:20' => 21
)

因此index [0]实际上是一个数组而不是数字,因此是错误。

您将不得不重新考虑输入数据的方式。

尝试尺寸:

将您的数据文件更改为

'00:00',19
'00:05',19
'00:10',21
'17:10',21
'17:15',21
'17:20',21

你的代码就是这样做的

$data = array();

$handle = fopen('tst.txt', 'r');
while (!feof($handle)) {
    $line = fgets($handle, 8192);
    list($time,$count) = explode(',',$line);
    $data[$time] = $count;
}
fclose($handle);
print_r($data);

这将生成以下数组

Array
(
    ['00:00'] => 19
    ['00:05'] => 19
    ['00:10'] => 21
    ['17:10'] => 21
    ['17:15'] => 21
    ['17:20'] => 21
)

我认为首先是你想要的。

编辑2

不要更改包裹,更改发送的内容

替换此行

$data[$time] = $count;

使用

$data[$time] = (int)$count;

应该这样做。