Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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);
//}
share|improve this question
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. –  DaveRandom Dec 14 '12 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? –  Jamie Bull Dec 14 '12 at 13:54
    
I'll answer that myself - yes it can $output = str_replace("'",'"',$output); –  Jamie Bull Dec 14 '12 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? –  DaveRandom Dec 14 '12 at 14:03
    

1 Answer 1

up vote 3 down vote accepted

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
)
share|improve this answer
    
Thanks but that's giving me an internal server error, I assume because not the right version of PHP. –  Jamie Bull Dec 14 '12 at 13:50
    
@jamiebull updated it, assuming the strings will be "simple" :) –  Jack Dec 15 '12 at 1:10
    
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. –  Jamie Bull Dec 15 '12 at 2:10
    
@JamieBull isn't that basically the second part of my answer? :) –  Jack Dec 15 '12 at 3:46
    
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? –  Jamie Bull Dec 15 '12 at 8:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.