Skip to content
Advertisement

How to load an array of external data in QuickChart?

I am looking to use QuickChart in my PHP project. I skimmed the documentation completely. But, everything in it has the data being statically loaded as an array. I am trying to load external data, that is generated from somewhere else, into the chart. To understand QuickChart, I tried to load data dynamically in the examples provided in the documentation.

<?php
require_once('QuickChart.php');  //the QuickChart.php file is copied in the same folder as this file.

$qc = new QuickChart();
$data = array(50, 60, 70, 180);  //loading data dynamically.
$qc->setConfig("{
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [{
      label: 'Users',
      data: $data  //line with error.
    }]
  }
}");

$a = $qc->getUrl();
$imageData = base64_encode(file_get_contents($a));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
?>

But, there is an error as follows.

Notice: Array to string conversion in C:xampphtdocsquickChartindex.php on line 12

Following is the example which I modified.

<?php
  require_once('../QuickChart.php');

  $qc = new QuickChart();
  $qc->setConfig("{
    type: 'bar',
    data: {
      labels: ['Q1', 'Q2', 'Q3', 'Q4'],
      datasets: [{
        label: 'Users',
        data: [50, 60, 70, 180]
      }]
    }
  }");

  echo $qc->getUrl();
?>

I searched for a while on Internet, but it looks like QuickChart isn’t as popular, so there aren’t many sources to read. What is the solution in this case?

Advertisement

Answer

That looks like a JSON String representaion of an array so for example

$jj = json_encode([50, 60, 70, 180]);

$qc->setConfig("{
    type: 'bar',
    data: {
      labels: ['Q1', 'Q2', 'Q3', 'Q4'],
      datasets: [{
        label: 'Users',
        data: $jj
      }]
    }
  }";

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement