Read values from an external XML using PHP json_encode and JavaScript

Example of how to read values from an external XML using PHP json_encode and JavaScript.

Read in the values from an external XML file:

http://www.dmssvr.com/dmsmon/sk_getxmldaytimeSQL.asp?id=990

The following PHP document reads in the values from the external XML file and creates an array, then, the array gets encoded (json_encode) and printed (echo) so the values can be retrieved by another page using HTML+JavaScript:

<?php

function DOMinnerHTML(DOMNode $element)
{
    $innerHTML = "";
    $children  = $element->childNodes;

    foreach ($children as $child)
    {
        $innerHTML .= $element->ownerDocument->saveHTML($child);
    }

    return $innerHTML;
}

$url = 'http://www.dmssvr.com/dmsmon/sk_getxmldaytimeSQL.asp?id=990';

$doc = new DOMDocument();
$doc->load($url);

$searchNode = $doc->getElementsByTagName('safe-total-instant-power');
foreach( $searchNode as $searchNode )
{
	$safe_total_instant_power = DOMinnerHTML($searchNode);
}

$searchNode = $doc->getElementsByTagName('safe-total-daily-kwh');
foreach( $searchNode as $searchNode )
{
	$safe_total_daily_kwh = DOMinnerHTML($searchNode);
}

$searchNode = $doc->getElementsByTagName('safe-total-weekly-kwh');
foreach( $searchNode as $searchNode )
{
	$safe_total_weekly_kwh = DOMinnerHTML($searchNode);
}

$searchNode = $doc->getElementsByTagName('safe-total-monthly-kwh');
foreach( $searchNode as $searchNode )
{
	$safe_total_monthly_kwh = DOMinnerHTML($searchNode);
}

$searchNode = $doc->getElementsByTagName('safe-total-lifetime-kwh');
foreach( $searchNode as $searchNode )
{
	$safe_total_lifetime_kwh = DOMinnerHTML($searchNode);
}

$searchNode = $doc->getElementsByTagName('weather');
foreach( $searchNode as $searchNode )
{
	$weather = DOMinnerHTML($searchNode);
}

// Initialize array that contains the solar values and then encodes for json and pads for cross domain
$a = array(
  'safe_total_instant_power' => $safe_total_instant_power,
  'safe_total_daily_kwh' => $safe_total_daily_kwh,
  'safe_total_weekly_kwh' => $safe_total_weekly_kwh,
  'safe_total_monthly_kwh' => $safe_total_monthly_kwh,
  'safe_total_lifetime_kwh' => $safe_total_lifetime_kwh,
  'weather' => $weather
);

echo $_GET['callback'].'('.json_encode($a) .')';

?>

The Following HTML+JavaScript document retrieves the values from the json_encode of the PHP page:

<style type="text/css">.containerFlexbox {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-evenly;
  /* align-items: center; */
  }
</style>
<div class="containerFlexbox">
  <section>
    <h2 class="text-align-center" id="outputTitle">&nbsp;
    </h2>
    <h2 class="text-align-center" id="loading">Loading solar data...
    </h2>
    <p>
      <canvas height="400" id="canvas" width="400"> 
      </canvas>
    </p>
  </section>
  <section>
    <h2 class="text-align-center" id="statsTitle">&nbsp;
    </h2>
    <div class="dataField" id="safe-total-instant-power">&nbsp;
    </div>
    <div class="dataField" id="safe-total-daily-kwh">&nbsp;
    </div>
    <div class="dataField" id="safe-total-weekly-kwh">&nbsp;
    </div>
    <div class="dataField" id="safe-total-monthly-kwh">&nbsp;
    </div>
    <div class="dataField" id="safe-total-lifetime-kwh">&nbsp;
    </div>
    <div class="dataField" id="weather">&nbsp;
    </div>
    <div class="dataField" id="time">&nbsp;
    </div>
  </section>
  <section style="width: 300px;">
    <div id="calculatorInfoTitle">&nbsp;
    </div>
    <div id="calculatorInfo">&nbsp;
    </div>
  </section>
  <section>
    <div id="calculator">&nbsp;
    </div>
  </section>
</div>
<script type="text/javascript">
  //Global variables
  var acKwOutput = 0;
  var isCalculatorOn = false;
  //clock stuff
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var radius = canvas.height / 2;
  ctx.translate(radius, radius);
  radius = radius * 0.90
  function drawClock() {
    drawFace(ctx, radius);
    drawNumbers(ctx, radius);
    drawTime(ctx, radius);
  }
  function drawFace(ctx, radius) {
    var grad;
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();
    grad = ctx.createRadialGradient(0, 0 ,radius * 0.95, 0, 0, radius * 1.05);
    grad.addColorStop(0, '#333');
    grad.addColorStop(0.5, 'white');
    grad.addColorStop(1, '#333');
    ctx.strokeStyle = grad;
    ctx.lineWidth = radius*0.1;
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
    ctx.fillStyle = '#333';
    ctx.fill();
  }
  function drawNumbers(ctx, radius) {
    var ang;
    var num;
    //ctx.font = radius * 0.15 + "px arial";
    ctx.font = radius * 0.09 + "px arial";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    for(num = 0; num < 11; num++){
      ang = (num + 1) * Math.PI / 6;
      ctx.rotate(ang);
      ctx.translate(0, radius * 0.85);
      ctx.rotate(-ang);
      if (num == 0)
      {
        ctx.fillText(num.toString() + "%", 0, 0);
      }
      else
      {
        ctx.fillText(num.toString() + "0%", 0, 0);
      }
      ctx.rotate(ang);
      ctx.translate(0, -radius * 0.85);
      ctx.rotate(-ang);
    }
  }
  function drawTime(ctx, radius){
    //var now = new Date();
    //var second = now.getSeconds();
    // seconds
    //second = (second*Math.PI/30);
    //var second = ((acKwOutput * 10) * Math.PI/20);
    acKwOutput = (10 * acKwOutput) / 12;
    if (acKwOutput > 10)
    {
      acKwOutput = 10;
    }
    var second = ((acKwOutput + 1) * Math.PI/6);
    drawHand(ctx, second, radius*0.9, radius*0.02);
  }
  function drawHand(ctx, pos, length, width) {
    ctx.beginPath();
    ctx.lineWidth = width;
    ctx.lineCap = "round";
    ctx.moveTo(0,0);
    ctx.rotate(pos);
    ctx.lineTo(0, length);
    ctx.stroke();
    ctx.rotate(-pos);
  }
  //end of clock stuff
  document.addEventListener('DOMContentLoaded', function() {
    setInterval(function(){ 
      var url = "https://feedback.uccs.edu/solar_data/solar_data.php";
      jQuery.ajax({	//Get the JSONP data from support_avail.php
        type: 'GET',
        url: url,
        //async: false,				//JSONP is always async
        timeout: 9000,
        contentType: "application/jsonp",
        dataType: 'jsonp',
        success: function(data) {
          if (!data.safe_total_instant_power)
          {
            sorryURL = "//www.uccs.edu/sengkiosk/unavail"; //assign url to unavailable page
            newWindow = window.open(sorryURL,'name','width=700,height=500,menubar=1,location=1,status=1,scrollbars=1,resizable=1,left=0,top=0');
            //^^^ opens unavaiable page in popup window
            if (window.focus) {newWindow.focus()}
            return false;
          }
          else
          {
            //clear loading message
            document.getElementById("loading").innerHTML = "";
            //add Output title
            document.getElementById("outputTitle").innerHTML = "System Output";  
            //add Stats title
            document.getElementById("statsTitle").innerHTML = "Stats";
            //add styles to the data fields
            var selects = document.getElementsByClassName("dataField");
            for(var i =0, il = selects.length;i<il;i++){
              selects[i].style.border = "1px solid #333333";
              selects[i].style.borderRadius = "4px";
              selects[i].style.padding = "10px";
              selects[i].style.backgroundColor = "#e2e2e2";
              selects[i].style.margin = "10px";
            }
            //Process data
            if (data.safe_total_instant_power.toString().length == 5)
            {
              var res = data.safe_total_instant_power.split("");
              acKwOutput = parseFloat(res[0] + res[1] + "." + res[2] + res[3] + res[4]);
            }
            else if (data.safe_total_instant_power.toString().length == 4)
            {
              var res = data.safe_total_instant_power.split("");
              acKwOutput = parseFloat(res[0] + "." + res[1] + res[2] + res[3]);
            }
            else if (data.safe_total_instant_power.toString().length == 3)
            {
              var res = data.safe_total_instant_power.split("");
              acKwOutput = parseFloat("0." + res[0] + res[1] + res[2]);
            }
            else if (data.safe_total_instant_power.toString().length == 2)
            {
              var res = data.safe_total_instant_power.split("");
              acKwOutput = parseFloat("0.0" + res[0] + res[1]);
            }
            else
            {
              acKwOutput = data.safe_total_instant_power;
            }
            var instantPower = "AC kW Output: " + acKwOutput + " kW";
            var dailyKwh = "Today: " + data.safe_total_daily_kwh + " kWh";
            var weeklyKwh = "This Week: " + data.safe_total_weekly_kwh + " kWh";
            var monthlyKwh = "This Month: " + data.safe_total_monthly_kwh + " kWh";
            var lifetimeKwh = "Lifetime: " + data.safe_total_lifetime_kwh + " kWh";
            var weather = "Weather: " + data.weather;
            var time = new Date();
            //Print data to webpage
            document.getElementById("safe-total-instant-power").innerHTML = instantPower;
            document.getElementById("safe-total-daily-kwh").innerHTML = dailyKwh;
            document.getElementById("safe-total-weekly-kwh").innerHTML = weeklyKwh;
            document.getElementById("safe-total-monthly-kwh").innerHTML = monthlyKwh;
            document.getElementById("safe-total-lifetime-kwh").innerHTML = lifetimeKwh;
            document.getElementById("weather").innerHTML = weather;
            document.getElementById("time").innerHTML = "Time of last reading: " + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();         
            drawClock();
            // Show the calculator  
            if (isCalculatorOn == false)
            {
              document.getElementById("calculatorInfoTitle").innerHTML = "<h3>Greenhouse Gas Equivalencies Calculator</h3>";
              document.getElementById("calculatorInfo").innerHTML = "<br><p>This greenhouse gas equivalencies calculator can help you understand abstract measurements into concrete terms, such as the annual emissions from cars, households, or power plants. Select kilowatt-hours of electricity as the unit and add the value from either today's, this Week's, this month's, or the total lifetime kilowatt-hours of this system.</p>";
              document.getElementById("calculator").innerHTML = "<iframe src='//www.epa.gov/sites/production/files/widgets/ghg_widget/widget.html' id='ghg_equivalencies' width='260' height='535' scrolling='no' frameborder='0' marginwidth='0' marginheight='0'></iframe> ";
              isCalculatorOn = true;
            }
            return false;
          }
          return false;
        },
        error: function() { //if no data then...
          //window.alert("ERROR!");	 
          return false;
        } 
      });
    }, 5000);
  }, false);
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *