使用PhpMyGraph从文件中绘制图形


Draw a graph from file using PhpMyGraph

在这些天里,我试图从使用PhpMyGraph5.0的文件中绘制图形,在作者的站点(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.');
    }
...

我已经尝试用以下强制转换来代替"throw Exception":

$value=(int)$value;

,但我只得到一个空图。

如果我手动粘贴MYFILE的内容到$data = array(PASTE_HERE);它可以工作,但是我不能手动操作。

我认为问题是关于值的数据类型,但是我不知道如何解决这个问题

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

该异常似乎是编码很糟糕,试着改变它,它应该给你的关键值,它发现的值不是数字,这可能有助于识别错误在哪里:-

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]实际上是一个数组,而不是一个数字,因此出现了错误。

你得重新考虑你输入数据的方式。

试试size:

把你的数据文件改成这样

'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;

应该可以了