0

Im trying to get multiple lists from a python script to PHP. Going off from this question Passing a Python list to php, Im using Json.

Python:

list1 = [1,2,3]
list2 = [4,5,6]
print(json.dumps(list1))
print(json.dumps(list2))

For PHP I tried multiple ways:

json_decode(exec("test.py", $return), true);

var_dump($return);

This gives the two lists as an array of strings.

(array(2) { [0]=> string(9) "[1, 2, 3]" [1]=> string(9) "[4, 5, 6]")

Using

$output = json_decode(exec("test.py", $return), true);

var_dump($output); 

only gives the second list as an array.

Using print(json.dumps([list1,list2])) in Python gives the two lists as a single string.

How can I get multiple lists as arrays in PHP? Or is there a better way to parse the lists in PHP?

1 Answers1

1

Your mixing things up. Your first python example produces 2 valid json string which together are invalid json.

Then exec returns the last line of output and stores each line as a single entry in the second argument ($return).

So you python should look like:

list1 = [1,2,3]
list2 = [4,5,6]
# Print one line of json
print(json.dumps([list1, list2]))

And PHP:

$output = exec("test.py");
$data = json_decode($output, true);

// OR
$output = [];
exec("test.py", $output);

$data = json_decode($output[0], true);

Code Spirit
  • 3,992
  • 4
  • 23
  • 34