0

I've tried to send data from php to python, I found a tutorial from here.

this is the code.

php

<?php
$data = array('1','4','67','34');
$result = shell_exec('python try.py ' . escapeshellarg(json_encode($data)));
$resultData = json_decode($result, true)
var_dump($resultData);
?>

python

#!/Python27/python
import sys, json

# Load the data that PHP sent us
try:
    data = json.loads(sys.argv[1])
except:
    print "ERROR"
    sys.exit(1)

# Send it to stdout (to PHP)
print json.dumps(data)

and output:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(4)
  [2]=>
  int(67)
  [3]=>
  int(34)
}

I try and succeed, but it's just an integer, I want a string.

I tried to replace the data

$data = array('tiger','dog','cow','lion');

but the result is NULL

5
  • 1
    A simple print repr(sys.argv[1]) in Python should show on which side (PHP or Python) the problem lies. Commented Nov 23, 2017 at 2:50
  • I'm not sure how python handles escaped args. I would try printing the raw sys.argv[1] to see if it's still escaped. Commented Nov 23, 2017 at 2:50
  • Also if these are going to be large arrays of data you may want to write it to a temp file and then pass the file path into python. Commented Nov 23, 2017 at 2:51
  • If this is on Windows, escapeshellargs won't help much; and there's no way for Python to salvage the args. Better use popen and pass the JSON per sys.stdin. Commented Nov 23, 2017 at 2:51
  • works-fine-on-my-end. Missing a semicolon in the php code (syntax error). But yeah definitely don't run a bunch of data through shell arguments, use stdin or a tmpfile. Also specify python2 when executing since python may some day refer to python3 (already does on some os's since several years back) .. and/or use python3 instead (python2 is legacy) ... oh and if I use the wrong python version (causing the shell command to fail), the php result is NULL Commented Nov 23, 2017 at 3:40

0

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.