如何从外部文件向php数组提供数据?

时间:2013-09-19 20:05:41

标签: php html

我正在使用phplot在网页中绘制图表,我有以下代码,

   <?php
     //Include the code
    require_once 'C:/xampp/htdocs/phplot-6.1.0/phplot.php';

     //Define the object
     $plot = new PHPlot();

    //Define some data

     $example_data = array(
     array('a',3),
     array('b',5),
     array('c',7),
     array('d',8),
     array('e',4),
     array('f',6),
      array('g',7)
      );
     $plot->SetDataValues($example_data);

     //Turn off X axis ticks and labels because they get in the way:
     $plot->SetXTickLabelPos('none');
     $plot->SetXTickPos('none');

      //Draw it
      $plot->DrawGraph();
       ?>

我不想像$ example_data那样定义数据,但我想从外部文件(如txt或json)读取或上传,请建议如何实现这一点以及外部文件的类型是什么要上传吗?

3 个答案:

答案 0 :(得分:4)

是的,你可以:

$file = 'your.json';
$example_data = json_decode( @file_get_contents( $file ) );

your.json(例如):

[["a",3],["b",5],["c",7],["d",8],["e",4],["f",6],["g",7]]

已更新!

用于创建动态json文件:

$data = array();

$data[] = array( 'a' , 3 );
$data[] = array( 'b' , 1 );
$data[] = array( 'c' , 2 );
$data[] = array( 'd' , 4 );
$data[] = array( 'e' , 8 );
$data[] = array( 'f' , 6 );
$data[] = array( '6' , 7 );

echo json_encode( $data );

另一种方式:

make_data.php

$data = array();

$data[] = array( 'a' , 3 );
$data[] = array( 'b' , 1 );
$data[] = array( 'c' , 2 );
$data[] = array( 'd' , 4 );
$data[] = array( 'e' , 8 );
$data[] = array( 'f' , 6 );
$data[] = array( '6' , 7 );

return $data;

并阅读:

$example_data = include( 'make_data.php' );

答案 1 :(得分:0)

喜欢这个吗?

   <?php
     //Include the code
    require_once 'C:/xampp/htdocs/phplot-6.1.0/phplot.php';

     //Define the object
     $plot = new PHPlot();

    //Define some data

     $example_data = json_decode(file_get_contents("some_external_file.json"),true);
     $plot->SetDataValues($example_data);

     //Turn off X axis ticks and labels because they get in the way:
     $plot->SetXTickLabelPos('none');
     $plot->SetXTickPos('none');

      //Draw it
      $plot->DrawGraph();
       ?>


some_external_file.json

{"a":3,"b":5,"c":7,"d":8,"e":4,"f":6,"g":7};

答案 2 :(得分:0)

似乎是一个相当常见的解决方案是简单地返回一个php数组。

include.php:

<?php
return array(14, 34, 342, 4252);

的index.php:

<?php

$data=include('include.php');