2

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);
//}
6
  • 4
    If you can have Python output the array with double quotes instead of single quotes, you can just json_decode() it without modification. Try and use an interoperable standard for this, JSON seems ideally suited. Commented Dec 14, 2012 at 13:31
  • This seems like the right way to go. I'll see if it's possible - although could it also be done as a string replace at the PHP end? Commented Dec 14, 2012 at 13:54
  • I'll answer that myself - yes it can $output = str_replace("'",'"',$output); Commented Dec 14, 2012 at 13:57
  • That is not a safe option. Consider ['Some string with a \' quote in it'] - the data will be modified. Does Python not have a json encoding function? Commented Dec 14, 2012 at 14:03
  • docs.python.org/2/library/json.html Commented Dec 14, 2012 at 14:06

1 Answer 1

4

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
)
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks but that's giving me an internal server error, I assume because not the right version of PHP.
@jamiebull updated it, assuming the strings will be "simple" :)
Thanks. I've cracked it now though. I would have used @Dave Random's json approach but it turns out my host doesn't include json as part of the pre-installed packages - which took hours of pointless going in circles to figure out. In the end I went with remove "[[", remove "]]", explode on "], [", foreach row, write each row, parsing it as you go along. Hacky as can be but it's working.
@JamieBull isn't that basically the second part of my answer? :)
It may well be. As I said, PHP's new to me (like, yesterday new). I'd actually missed the second part to your answer. I just had a quick go at implementing it your way and I'm sure the problem's at my end. Should I be passing in my $output as the $s variable in your snippet then writing to the CSV with fputcsv($data); beacause that's outputting a blank CSV?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.