如何在Google带注释的时间线图中解析PHP变量?

时间:2013-05-24 23:11:25

标签: php javascript

我想使用PHP数组中的变量生成带有Google注释的时间轴图,但始终会出现“未定义变量”错误。

<?php

$years = array(1991, 1992, 1993, 1994);
$graphs = array(20, 30, 40, 50);

echo<<<_END

<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='http://www.google.com/jsapi'>
</script>
<script type='text/javascript'>

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

      google.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = new google.visualization.DataTable();

        data.addColumn('date', 'Date');

        data.addColumn('number', 'Data');   

        data.addRows([

    <?php

    for ($i=0; $i<=3; $i++){

    echo "[new Date(" . $years[$i] . ", 1, 1), " . $graphs[$i] . "],";

    /* output 

    [new Date(1991, 1, 1), 20],

    [new Date(1992, 1, 1), 30],

    etc..

    */

    }

    ?>    

        ]);

        var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div1'));

        chart.draw(data, {displayAnnotations: true});

      }

</script> 
</head>
<body>

<div id='chart_div1' style='width: 700px; height: 240px;'>
</div>

</body>

</html>
_END;

?>

1 个答案:

答案 0 :(得分:0)

你为什么要在你的heredoc里面做一个php循环?只需关闭你的PHP代码,让html代码单独解析 -

<?php

$years = array(1991, 1992, 1993, 1994);
$graphs = array(20, 30, 40, 50);

?>

<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='http://www.google.com/jsapi'>
</script>
<script type='text/javascript'>

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

      google.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = new google.visualization.DataTable();

        data.addColumn('date', 'Date');

        data.addColumn('number', 'Data');   

        data.addRows([

    <?php

    for ($i=0; $i<=3; $i++){

    echo "[new Date(" . $years[$i] . ", 1, 1), " . $graphs[$i] . "],";

    /* output 

    [new Date(1991, 1, 1), 20],

    [new Date(1992, 1, 1), 30],

    etc..

    */

    }

    ?>    

        ]);

        var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div1'));

        chart.draw(data, {displayAnnotations: true});

      }

</script> 
</head>
<body>

<div id='chart_div1' style='width: 700px; height: 240px;'>
</div>

</body>

</html>

这样做的代码运行正常 - 请参阅http://phpfiddle.org/main/code/fki-b1i