Guest User

Json export for google charts

a guest
Jan 2nd, 2017
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1. <?php
  2. $solartracker = "/home/pi/Documents/Projects/ArduinoSerialImport/solartracker.db";
  3. $dsn = "sqlite:$solartracker";
  4.  
  5. try {
  6.     $db = new PDO($dsn);
  7.     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  8. } catch (PDOException $error) {
  9.     echo "Failed to connect to the database using DSN:<br>$dsn<br>";
  10.     throw $error;
  11. }
  12.  
  13. $stmt = $db->prepare("SELECT voltage, current, datestamp FROM stuffToPlot");
  14. $stmt->execute();
  15.  
  16. $rows = array();
  17. $table = array();
  18.  
  19. $table['cols'] = array(
  20.     array('label' => 'Time', 'type' => 'date'),
  21.     array('label' => 'Power', 'type' => 'number')
  22. );
  23.  
  24. while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  25.     $voltage[] = $row['voltage'];
  26.         $current[] = $row['current'];
  27.  
  28.         $voltage = array();
  29.         $current = array();
  30.  
  31.  
  32.     $date1 = new DateTime();
  33.     $date2 = "Date(".date_format($date1, 'Y').", ".((int) date_format($date1, 'm') - 1).", ".date_format($date1, 'd').", ".date_format($date1, 'H').", ".date_format($date1, 'i').", ".date_format($date1, 's').")";
  34.  
  35.     $power = array();
  36.     foreach ($voltage as $key => $door){
  37.              $power[] = $door * $current[$key];}
  38.  
  39.  
  40.     $temp = array();
  41.     $temp[] = array('v' => (float) $power);
  42.     $temp[] = array ('v' => (string) $date2);
  43.     $rows[] = array ('c' => $temp);
  44.  
  45. }
  46.  
  47. $table['rows'] = $rows;
  48.  
  49. echo json_encode($table);
  50.  
  51. $fp = fopen('data.json', 'w');
  52. fwrite($fp, json_encode(array('cols' =>$table)));
  53.  
  54. fclose($fp);
  55. ?>
Add Comment
Please, Sign In to add comment