Execute Google Chart API (Javascript) in php file

2020-01-29 18:30发布

问题:

I am creating a mail in php, in a wordpress plugin, and would like to include an image created by the google chart api. I tried the following:

<?php
$message.= <<<HTML

      <script>
    google.charts.load('current', {
        'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Year', 'Sales', 'Expenses'],
            ['2013', 1000, 400],
            ['2014', 1170, 460],
            ['2015', 660, 1120],
            ['2016', 1030, 540]
        ]);

        var options = {
            title: 'Company Performance',
            hAxis: {
                title: 'Year',
                titleTextStyle: {
                    color: '#333'
                }
            },
            vAxis: {
                minValue: 0
            }
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    </script>

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    HTML;   

        $message.=<<<HTML

<h1> test message </h1>
    HTML;   

    $to = "test@test.com";
    $subject = "test message";
    $headers = "test message";

    add_filter( 'wp_mail_content_type', 'set_html_content_type' );
    wp_mail( $to, $subject, $message,$headers );
    remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
?>

My problem is that Javascript cannot be executed in a delivered mail. Hence, I am looking for a way to execute Javascript inside the script.

Any suggestions how to execute javascript in a php file to get the resulting google-api link?

I appreciate a working example!

PS.: My php version is:

> php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

回答1:

google charts have a native method (getImageURI)
it creates a base64 string representation of the chart
which can be included in the src attribute of an img element
or saved to a file as .png

see Printing PNG Charts for more info

in addition, you should wait for the chart's 'ready' event to fire,
before grabbing the image

to send the chart image in an email, recommend having a page that draws the chart
then when the 'ready' event fires, sends the image string via ajax to the controller that sends the email...

see following snippet for example of getting image...

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2013',  1000,      400],
      ['2014',  1170,      460],
      ['2015',  660,       1120],
      ['2016',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
      hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
      vAxis: {minValue: 0},
      legend: {
        position: 'top'
      }
    };

    var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
    google.visualization.events.addListener(chart, 'ready', function () {
      document.getElementById('image_div').innerHTML = '<img src="' + chart.getImageURI() + '" />';
    });
    chart.draw(data, options);
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Chart</div>
<div id="chart_div"></div>
<div>Image</div>
<div id="image_div"></div>

EDIT

taking from the example above, when the chart's 'ready' event fires,
send the image string back to the same page via ajax post

then in php, check if the image was received

if received, send email, otherwise draw chart

following is a primitive example of the workflow...

<?php
  if(isset($_POST['chartImage'])) {
    $to = "test@test.com";
    $subject = "test message";
    $headers = "test message";
    $message = $_POST['chartImage'];

    add_filter( 'wp_mail_content_type', 'set_html_content_type' );
    wp_mail( $to, $subject, $message, $headers );
    remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
  } else {
?>
  <script>
    google.charts.load('current', {
      callback: function () {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2013',  1000,      400],
          ['2014',  1170,      460],
          ['2015',  660,       1120],
          ['2016',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          hAxis: {title: 'Year',  titleTextStyle: {color: '#333'}},
          vAxis: {minValue: 0},
          legend: {
            position: 'top'
          }
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        google.visualization.events.addListener(chart, 'ready', function () {
          // send chart image
          $.ajax({
            type: 'POST',
            url: 'mail.php',
            data: {
              'chartImage': chart.getImageURI(),
            },
            success: function(){
              console.log('email sent');
            }
          });
        });
        chart.draw(data, options);
      },
      packages: ['corechart']
    });
  </script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>
<?php
  }
?>


回答2:

Not exactly the usage of google chart api, but this might actually help you.

Google also have their Image Charts (which is deprecated, however they stated they have no plans to turn it off). You can use the Image Charts to generate the graph that you want and get an image in return.

I took the data and generated this image:

Which can be generated using this link.


I know this is not exactly the same graphics as the Chart API (and their image charts missing some great things like opacity and stuff) but It might be the quick solution that you are looking for.

And a live snippet:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    google.charts.load('current', {
        'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Year', 'Sales', 'Expenses'],
            ['2013', 1000, 400],
            ['2014', 1170, 460],
            ['2015', 660, 1120],
            ['2016', 1030, 540]
        ]);

        var options = {
            title: 'Company Performance',
            hAxis: {
                title: 'Year',
                titleTextStyle: {
                    color: '#333'
                }
            },
            vAxis: {
                minValue: 0
            }
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
</script>
<div id="chart_div"></div> 
<img src="https://chart.googleapis.com/chart?cht=lc&chd=t:1000,1170,660,1030|400,460,1120,540&chds=a&chxr=1,0,1200,300&chxt=x,y&chxl=0:|2013|2014|2015|2016&chs=600x200&chm=B,c2d1f0,0,0,0|B,f5c4b8,1,1,0&chtt=Company%20Performance&chts=000000,20,l&chdl=Sales|Expenses&chco=0000FF,FF0000">



回答3:

You can use canvas2html.js to export chart as data URI

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <script src="canvas2html.js"></script>
  <div id="chart_div"></div>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
  </script>
  <script type="text/javascript">
    google.charts.load('current', {
      'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2013', 1000, 400],
        ['2014', 1170, 460],
        ['2015', 660, 1120],
        ['2016', 1030, 540]
      ]);

      var options = {
        title: 'Company Performance',
        hAxis: {
          title: 'Year',
          titleTextStyle: {
            color: '#333'
          }
        },
        vAxis: {
          minValue: 0
        }
      };

      var chart = new google.visualization
                 .AreaChart(document.getElementById('chart_div'));
      chart.draw(data, options);
      html2canvas(document.getElementById('chart_div'))
        .then(function(canvas) {
          var dataURL = canvas.toDataURL();
          // `dataURL` : `data URI` of chart drawn on `<canvas>` element
          console.log(dataURL);
        })
    }
  </script>
</body>

</html>

plnkr http://plnkr.co/edit/WPeiFuSdFIYP9297yHYN?p=preview



回答4:

I would render the charts using PhantomJS or any other headless browser good with js. Please see this link for examples:

http://johanndutoit.net/google-charts-js-api-server-side-nodejs/

Since you're using php you need to wrap the request with something like this:

http://jonnnnyw.github.io/php-phantomjs/