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?

2
  • You should just be able to do this in python: print([list1, list2]) Commented Nov 2, 2021 at 18:21
  • @C_Z_ This just gives one long string same as print(json.dumps([list1,list2])) Commented Nov 2, 2021 at 18:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your second example is what worked for me. Now each list is accessible as an array through output[]

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.