Jamie Bull
Jamie Bull

Reputation: 13529

Parsing Python array in PHP

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);
//}

Upvotes: 2

Views: 2162

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173572

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
)

Upvotes: 4

Related Questions