Re: Help with xml

1,139 views
Skip to first unread message

asgallant

unread,
Sep 24, 2012, 1:09:21 PM9/24/12
to google-visua...@googlegroups.com
There are multiple ways to populate the charts via PHP.  The two primary ways are: 1) populate the javascript with data from PHP, or 2) build a PHP script that fetches your data and returns it as JSON in response to an AJAX request from javascript.

The first would look like this:

function drawChart ({
    var data new google.visualization.DataTable();
    data.addColumn('string''Name');
    data.addColumn('number''Value');
<?php
    // $data is an array of chart data
    foreach ($data as $row{
        echo "data.addRow(['{$row[0]}', {$row[1]});";
    }
?>
    
    var chart new google.visualization.LineChart('chart_div');
    chart.draw(data{/*options*/});
} 

The second would look like this on the javascript end:

function drawChart ({
    $.ajax({
        dataType'json',
        url'/path/to/data/source.php',
        successfunction (json{
            // convert json into DataTable object
            var data new google.visualization.DataTable(json); 
            // create and draw chart 
            var chart new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data{/*options*/});
        }
    });
}

and this on the PHP end:

$query = $db->prepare($queryStr);
$query->execute($params);
$results = $query->fetchAll(PDO::FETCH_ASSOC);

// $cols is an array of MySQL column names mapped to DataTable type and label
foreach ($cols as $colKey => $col) {
if ($col['type'] == 'tooltip') {
$output['dataTable']['cols'][] = array ('type' => 'string', 'role' => 'tooltip', 'p' => array ('role' => 'tooltip'));
}
else {
$output['dataTable']['cols'][] = array ('type' => $col['type'], 'label' => $col['label']);
}
}

foreach ($results as $row) {
$temp = array ();
foreach ($cols as $colKey => $col) {
$temp[] = array('v' => ($col['type'] == 'number') ? (float) str_replace(',', '', $row[$colKey]) : $row[$colKey]);
}
$output['dataTable']['rows'][] = array ('c' => $temp);
}

$output['options'] = $setup['options'];
$output['chartType'] = $setup['chartType'];

// set up header and output json (first two prevent IE from caching queries)
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($output);

You would have to change from querying the database to reading the XML there.

You can also skip PHP entirely and grab the XML doc directly:

function drawChart ({
    $.ajax({
        dataType'xml',
        url'/path/to/xml/doc.xml',
        successfunction (xml{
            // convert xml into DataTable object
            var data new google.visualization.DataTable();
            // parse xml for columns and add via:
            data.addColumn(/*data type*//*column label*/);
            
            // parse xml for rows of data and add via:
            data.addRow(/*array of row data*/);
            
            // create and draw chart 
            var chart new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data{/*options*/});
        }
    });
}

Precisely how you go about parsing the XML there depends on the structure of the XML, but that should be good enough to get you started.

Also note that these AJAX examples require the jQuery js library.  They can be done without it, but the code is more complex.  Add the library with this script tag, before the chart code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.jstype="text/javascript"></script> 

On Monday, September 24, 2012 9:36:29 AM UTC-4, thecatz wrote:
Hello, i'm a real newbie on javascript, i only know php, i realy need help to how populate my chart with an xml. On all example of the documentation the data are directly on the javascript, and i need to import the data from a xml.

1st i rlly dont know how to make this on javascript, but only on php, can i combine php with google chart ? is the re any example for helping me with this ?

thx a lot

thecatz

unread,
Sep 25, 2012, 5:13:57 AM9/25/12
to google-visua...@googlegroups.com
Thx a lot for your help, i've tryed something like this :

i use your first example.

This is my xml :


<?xml version="1.0" encoding="utf-8"?>
<Export>
  <Columns>
    <Dim1>Heures</Dim1>
    <Metric1>Visites</Metric1>
    <Var1>Visites var</Var1>
    <Diff1>Visites Diff</Diff1>
    <Rat1>Visites rat</Rat1>
    <Metric12>% Visites</Metric12>
    <Var12>% Visites var</Var12>
    <Diff12>% Visites Diff</Diff12>
    <Metric2>Pages vues</Metric2>
    <Var2>Pages vues var</Var2>
    <Diff2>Pages vues Diff</Diff2>
    <Rat2>Pages vues rat</Rat2>
    <Metric5>Pages vues / visites</Metric5>
    <Var5>Pages vues / visites var</Var5>
    <Diff5>Pages vues / visites Diff</Diff5>
  </Columns>
  <Row Dim1="0h" Metric1="4844" Var1="" Diff1="4844" Rat1="0,018716288271023" Metric12="0,018716288271023" Var12="" Diff12="-2147483648" Metric2="143891" Var2="" Diff2="143891" Rat2="0,101175509354574" Metric5="29,7049958711808" Var5="" Diff5="29,7049958711808" />
  <Row Dim1="1h" Metric1="2974" Var1="" Diff1="2974" Rat1="0,0114909664157767" Metric12="0,0114909664157767" Var12="" Diff12="-2147483648" Metric2="9140" Var2="" Diff2="9140" Rat2="0,00642669906735518" Metric5="3,07330195023537" Var5="" Diff5="3,07330195023537" />
  <Row Dim1="2h" Metric1="1882" Var1="" Diff1="1882" Rat1="0,00727168755699118" Metric12="0,00727168755699118" Var12="" Diff12="-2147483648" Metric2="9592" Var2="" Diff2="9592" Rat2="0,00674451832101432" Metric5="5,09670563230606" Var5="" Diff5="5,09670563230606" />
  <Row Dim1="3h" Metric1="1624" Var1="" Diff1="1624" Rat1="0,00627482496947591" Metric12="0,00627482496947591" Var12="" Diff12="-2147483648" Metric2="7336" Var2="" Diff2="7336" Rat2="0,00515823461248552" Metric5="4,51724137931035" Var5="" Diff5="4,51724137931035" />
  <Row Dim1="4h" Metric1="1506" Var1="" Diff1="1506" Rat1="0,00581889556898444" Metric12="0,00581889556898444" Var12="" Diff12="-2147483648" Metric2="9304" Var2="" Diff2="9304" Rat2="0,00654201401779788" Metric5="6,17795484727756" Var5="" Diff5="6,17795484727756" />
  <Row Dim1="5h" Metric1="1915" Var1="" Diff1="1915" Rat1="0,00739919323678964" Metric12="0,00739919323678964" Var12="" Diff12="-2147483648" Metric2="7439" Var2="" Diff2="7439" Rat2="0,00523065802648306" Metric5="3,8845953002611" Var5="" Diff5="3,8845953002611" />
  <Row Dim1="6h" Metric1="4425" Var1="" Diff1="4425" Rat1="0,0170973525184304" Metric12="0,0170973525184304" Var12="" Diff12="-2147483648" Metric2="20688" Var2="" Diff2="20688" Rat2="0,0145465591143812" Metric5="4,67525423728814" Var5="" Diff5="4,67525423728814" />
  <Row Dim1="7h" Metric1="9232" Var1="" Diff1="9232" Rat1="0,0356706798757399" Metric12="0,0356706798757399" Var12="" Diff12="-2147483648" Metric2="55467" Var2="" Diff2="55467" Rat2="0,0390010631475919" Metric5="6,00812391681109" Var5="" Diff5="6,00812391681109" />
  <Row Dim1="8h" Metric1="17954" Var1="" Diff1="17954" Rat1="0,0693708174273218" Metric12="0,0693708174273218" Var12="" Diff12="-2147483648" Metric2="115563" Var2="" Diff2="115563" Rat2="0,0812569610854231" Metric5="6,43661579592291" Var5="" Diff5="6,43661579592291" />
  <Row Dim1="9h" Metric1="26848" Var1="" Diff1="26848" Rat1="0,103735530037247" Metric12="0,103735530037247" Var12="" Diff12="-2147483648" Metric2="210174" Var2="" Diff2="210174" Rat2="0,14778173411185" Metric5="7,8282926102503" Var5="" Diff5="7,8282926102503" />
  <Row Dim1="10h" Metric1="27323" Var1="" Diff1="27323" Rat1="0,105570839064649" Metric12="0,105570839064649" Var12="" Diff12="-2147483648" Metric2="158014" Var2="" Diff2="158014" Rat2="0,111105954751538" Metric5="5,78318632653808" Var5="" Diff5="5,78318632653808" />
  <Row Dim1="11h" Metric1="25643" Var1="" Diff1="25643" Rat1="0,0990796408203638" Metric12="0,0990796408203638" Var12="" Diff12="-2147483648" Metric2="124120" Var2="" Diff2="124120" Rat2="0,0872737295667533" Metric5="4,84030729633818" Var5="" Diff5="4,84030729633818" />
  <Row Dim1="12h" Metric1="19769" Var1="" Diff1="19769" Rat1="0,0763836298162373" Metric12="0,0763836298162373" Var12="" Diff12="-2147483648" Metric2="102729" Var2="" Diff2="102729" Rat2="0,0722328630733403" Metric5="5,19646921948505" Var5="" Diff5="5,19646921948505" />
  <Row Dim1="13h" Metric1="22112" Var1="" Diff1="22112" Rat1="0,0854365330819282" Metric12="0,0854365330819282" Var12="" Diff12="-2147483648" Metric2="111983" Var2="" Diff2="111983" Rat2="0,078739720094052" Metric5="5,06435419681621" Var5="" Diff5="5,06435419681621" />
  <Row Dim1="14h" Metric1="25458" Var1="" Diff1="25458" Rat1="0,0983648362517967" Metric12="0,0983648362517967" Var12="" Diff12="-2147483648" Metric2="116536" Var2="" Diff2="116536" Rat2="0,0819411162487203" Metric5="4,57757875716867" Var5="" Diff5="4,57757875716867" />
  <Row Dim1="15h" Metric1="22602" Var1="" Diff1="22602" Rat1="0,0873297992365114" Metric12="0,0873297992365114" Var12="" Diff12="-2147483648" Metric2="92426" Var2="" Diff2="92426" Rat2="0,0649884122537604" Metric5="4,08928413414742" Var5="" Diff5="4,08928413414742" />
  <Row Dim1="16h" Metric1="27549" Var1="" Diff1="27549" Rat1="0,106444059780845" Metric12="0,106444059780845" Var12="" Diff12="-2147483648" Metric2="89075" Var2="" Diff2="89075" Rat2="0,0626321903090441" Metric5="3,23332970343751" Var5="" Diff5="3,23332970343751" />
  <Row Dim1="17h" Metric1="15152" Var1="" Diff1="15152" Rat1="0,0585444260698886" Metric12="0,0585444260698886" Var12="" Diff12="-2147483648" Metric2="38715" Var2="" Diff2="38715" Rat2="0,0272220628438354" Metric5="2,55510823653643" Var5="" Diff5="2,55510823653643" />
</Export>

and this my try, but i dont really understanding how to get the row Dim1 ans row Metric 1 :


<?php

$sxml = simplexml_load_file('chartToday.xml');
foreach ($sxml->Row as $row) {
    $hours[] = $row["Dim1"];
    $metric[] = $row["Metric1"];
  
}

$sxml = simplexml_load_file('chartYesterday.xml');
foreach ($sxml->Row as $row) {
    $hours2[] = $row["Dim1"];
    $metric2[] = $row["Metric1"];
  
} ?>

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);

    function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('Hours', 'Metric1', 'Metrric2');


        var options = {
          title: 'My test Xhart',
          hAxis: {title: 'Hours',  titleTextStyle: {color: 'blue'}}
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Do you have any idea ?

thx

thecatz

unread,
Sep 25, 2012, 7:29:50 AM9/25/12
to google-visua...@googlegroups.com
finaly ive done this, but the page is blank :

can you tel me where is the problem ?


<html>
  <head>
 <script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Dim1');
    data.addColumn('number', 'Metric1');
 
       <?php $sxml = simplexml_load_file('graph.xml');

foreach ($sxml->Row as $row) {
            echo "data.addRow(['{$row['Dim1']}', {$row['Metric1']}]);";
        }
    ?>
    var chart = new google.visualization.BarChart('chart_div');

     chart.draw(data, options);
}
</script>
  </head>
  <body>
    <div id='chart_div'></div>
  </body>
</html>

asgallant

unread,
Sep 25, 2012, 2:40:59 PM9/25/12
to google-visua...@googlegroups.com
Can you post the javascript that is rendered by the server?

thecatz

unread,
Sep 26, 2012, 5:05:40 AM9/26/12
to google-visua...@googlegroups.com
<html>
  <head>
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'heures');
    data.addColumn('number', 'metric');
    data.addRow(['0h', 5347);data.addRow(['1h', 3121);data.addRow(['2h', 2362);data.addRow(['3h', 1591);data.addRow(['4h', 1692);data.addRow(['5h', 2206);data.addRow(['6h', 4684);data.addRow(['7h', 10821);data.addRow(['8h', 19478);data.addRow(['9h', 22051);	
	  var options = {
          title: 'test',
          hAxis: {title: 'heures',  titleTextStyle: {color: 'red'}}
        };

		
    var chart = new google.visualization.BarChart('chart_div');
     chart.draw(data, options);
}


</script>
  </head>
  <body>
   

asgallant

unread,
Sep 26, 2012, 1:17:22 PM9/26/12
to google-visua...@googlegroups.com
Your data.addRow(...) statements are missing the closing "]" at the end, ie:

data.addRow(['0h'5347);

should be:

data.addRow(['0h'5347]);

Also, you need to pass the DOM element object for the container div to the chart constructor, not the id of the container div, so this:

var chart new google.visualization.BarChart('chart_div');

should be this:

var chart new google.visualization.BarChart(document.getElementById('chart_div'));

Make those fixes and it should work (see example here: http://jsfiddle.net/asgallant/mTnk8/).

thecatz

unread,
Sep 27, 2012, 3:43:14 AM9/27/12
to google-visua...@googlegroups.com
ok i've fixe this line :


var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

and the javascript rendered by the server this time say this :

data.addRow([0h, 5347);data.addRow([1h, 3121);data.addRow([2h, 2362);data.addRow([3h, 1591);data.addRow([4h, 1692);data.addRow([5h, 2206);data.addRow([6h, 4684);data.addRow([7h, 10821);data.addRow([8h, 19478);data.addRow([9h, 22051);

And i understand that i need those thing :
data.addRow(['0h'5347]);

so i need to modifiy : <?php

$sxml = simplexml_load_file('graph.xml');
foreach ($sxml->Row as $row) {
echo "data.addRow([{$row[Dim1]}, {$row[Metric1]});";
}
?>

but have any idea to make this :) i just know that i need to put, result of $row[Dim1] on ' ' and to close result with a ]





asgallant

unread,
Sep 27, 2012, 10:36:20 AM9/27/12
to google-visua...@googlegroups.com
It should be:

echo "data.addRow([{$row[Dim1]}, {$row[Metric1]}]);";

thecatz

unread,
Sep 28, 2012, 4:46:52 AM9/28/12
to google-visua...@googlegroups.com
That work perfectly, another time thx a lot for your precious help, i've tried to put "2 chart" in one : like the demo : https://developers.google.com/chart/interactive/docs/gallery/areachart

but my problem is that the data for my second chart is from another xml, so i've tried to make this :

i'm loading the second xml : $sxml2 = simplexml_load_file('graphyesterday.xml');
i've added a third  Column : data.addColumn('number2', 'yesterday');

and here is my problem, i don't know how to wright it right : foreach ($sxml->Row as $row) AND ($sxml2->Row as $row2)

this is my complete code :


<script type='text/javascript'>
google.load('visualization', '1', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'heures');
    data.addColumn('number', 'today');
    data.addColumn('number2', 'yesterday');

    <?php
        $sxml = simplexml_load_file('graph.xml');
        $sxml2 = simplexml_load_file('graphyesterday.xml');
foreach ($sxml->Row as $row) AND ($sxml2->Row as $row2) {
           echo "data.addRow([ '{$row[Dim1]}', {$row[Metric1]} , {$row2[Metric1]}]);";
        }
    ?>

   
      var options = {
          title: 'test',
          hAxis: {title: 'heures',  titleTextStyle: {color: 'red'}}
        };

       

thecatz

unread,
Sep 28, 2012, 5:18:45 AM9/28/12
to google-visua...@googlegroups.com
there is my nex try :)

  <?php
    $sxml = simplexml_load_file('graph.xml');
    $sxml2 = simplexml_load_file('graphier.xml');
    foreach ($sxml->Row as $hey=>$row){
        echo "data.addRow([ '{$row[Dim1]}', {$row[Metric1]} , {$sxml2->Row[$hey][Metric1]}]);";
    }
?>

but my navigator say this :

data.addRow([ '0h', 6981 , ]);data.addRow([ '1h', 3339 , ]);data.addRow([ '2h', 2442 , ]);

As you can see the third column didn't acept datas from the second xml :(


asgallant

unread,
Sep 28, 2012, 10:41:37 AM9/28/12
to google-visua...@googlegroups.com
In order to match the two data sets, they would have to have the same keys or indices (ie, $hey in $sxml->Row must match a key or index in $sxml2->Row).  Take a look at a debug output of the two arrays to see if they match:

var_dump($sxml->Row);
var_dump($sxml2->Row);

thecatz

unread,
Oct 24, 2012, 4:14:32 AM10/24/12
to google-visua...@googlegroups.com
Thx for your help i'll try this

thecatz

unread,
Oct 24, 2012, 5:09:07 AM10/24/12
to google-visua...@googlegroups.com
Finally i realy don't understand what i ve to do :)  sorry !

where i've to put this :

var_dump($sxml->Row);
var_dump($sxml2->Row);

thx for your help !


<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    google.load('visualization', '1', {packages: ['corechart']});
    google.setOnLoadCallback(drawChart);

    function drawChart () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'heures');
    data.addColumn('number', 'today');
    data.addColumn('number2', 'yesterday');


   <?php
    $sxml = simplexml_load_file('graph.xml');
    $sxml2 = simplexml_load_file('graphier.xml');
    foreach ($sxml->Row as $hey=>$row){
        echo "data.addRow([ '{$row[Dim1]}', {$row[Metric1]} , {$sxml2->Row[$hey][Metric1]}]);";
    }
?>

      var options = {
          title: 'test',
          hAxis: {title: 'heures',  titleTextStyle: {color: 'red'}}
        };

      }

asgallant

unread,
Oct 24, 2012, 11:30:19 AM10/24/12
to google-visua...@googlegroups.com
Try this:

<?php
    $sxml = simplexml_load_file('graph.xml');
    $sxml2 = simplexml_load_file('graphier.xml');
    var_dump($sxml);
    var_dump($sxml2);
?>
Reply all
Reply to author
Forward
0 new messages