abcdxx
abcdxx

Reputation: 207

I have to pass an array from a php file to python file but my code is giving output NULL

PHP code:

<?php
$data = array('1','4','67','34');

$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)));

$resultData = json_decode($result, true);

var_dump($resultData);


?>

Python Code:

import sys, json

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

# Generate some data to send to PHP
result = {'23','4'}

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

Upvotes: 1

Views: 3620

Answers (2)

antonigiske
antonigiske

Reputation: 61

Add 2>&1 (stdout & stderr) behind the command like so:

$result = shell_exec('C:/Python27/python C:/xampp/htdocs/123.py ' . escapeshellarg(json_encode($data)) . ' 2>&1');

Upvotes: 1

furas
furas

Reputation: 142651

There is incorrect data for json.dump() in Python

# Generate some data to send to PHP
result = {'23','4'}

So this give error, not json string

import sys, json

# Generate some data to send to PHP
result = {'23','4'}

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

and PHP get NULL as $result from Python so you get NULL on screen - in browser

Use (for example):

# Generate some data to send to PHP
result = {'a':'23','b':'4'}

and json.dump() will work fine.

Upvotes: 1

Related Questions