drwu24647 2012-12-14 13:26
浏览 224
已采纳

用PHP解析Python数组

I have a Python script running on my server that creates a 2D list like so:

[['Header1', 'Header2', 'Header3'], ['2012-09-10 00:11:00', '61.3', '57.0'], ...]

I pass this back to the PHP script which is running my webpage. Here's the PHP I'm currently using to get the array. I get the rows, but obviously with an unwanted [[ at the start and ]] at the end.

exec("python weatherdata.py $stationID $startdate $enddate", $pyoutput);
$vars = explode("], [", $pyoutput[0]);

For the sake of explaining what I actually want to do, since there's bound to be a "proper" solution (I'm not at all familiar with PHP), what I want to do is adapt the code from here which download a CSV file to the user, but uses mySQL to populate it. The set-up part here works fine.

Edited in response to Jack's answer below

// Commented out my working parsing part
// remove the start and end square braces then split into rows
//$output = str_replace("[[","",$pyoutput);
//$output = str_replace("]]","",$output);
//$rows = explode("], [", $output[0]);

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

foreach (preg_split('/],\s*\[/', trim($pyoutput, '[]')) as $row) {
        $data= preg_split("/',\s*'/", trim($row, "'"));
        fputcsv($data);
}
// Commented out my working write to CSV part
// write rows
//foreach ($rows as $row){
//    $row = str_replace("'","",$row);
//    $row = explode(",", $row);
//    fputcsv($output, $row);
//}
  • 写回答

1条回答 默认 最新

  • doujiu5464 2012-12-14 13:39
    关注

    Not sure whether this is viable for you, but since PHP 5.4 it supports the short array syntax, e.g. [1, 2, 3] instead of array(1, 2, 3).

    So, you could just use evil ... I mean eval():

    $vars = eval(`python weatherdata.py $stationID $startdate $enddate`);
    

    Otherwise, if the array syntax is always in that format, just break it apart with preg_split(), first on square brackets and then on single quotes:

    foreach (preg_split('/],\s*\[/', trim($s, '[]')) as $row) {
            $data = preg_split("/',\s*'/", trim($row, "'"));
            print_r($data);
    }
    

    Output:

    Array
    (
        [0] => Header1
        [1] => Header2
        [2] => Header3
    )
    Array
    (
        [0] => 2012-09-10 00:11:00
        [1] => 61.3
        [2] => 57.0
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?