简体   繁体   中英

Passing a JSON between PHP and Python

I need to pass data from a PHP page to a Python script and back. I do it with a form that reminds to a page with this PHP code:

<html>
    <body>
        <h1>Project</h1>
        <h2>Results</h2>

    </body>
</html>

<?php 
    $myHotel->name = $_POST["NAME"];
    $hotel_data = json_encode($myHotel); ;
    $command = escapeshellcmd("/var/www/html/test.py $hotel_data");
    $resultAsString = exec($command);
?>

The JSON is sent back from the Python script:

#!/usr/bin/env python
import sys
import json

print(sys.argv[1]);

The problem, is that i send a JSON string like this:

{"name":"Hotel Roma Sud"}

And I receive something like this:

{name:Hotel Roma Sud}

How can I receive a JSON string or manage to have one? I tried with exec(), json_encode, json_decode... Thanks

You need to modify the script calling the command to avoid " getting parsed out by the bash - in order to give Python correct JSON string the argument should look like this - python test.py "{""name"":""Hotel Roma Sud""}" - this way Python receives '{"name":"Hotel Roma Sud"}' for argv[1] which you can parse with json.loads . It's not very clean solution though, so I'd probably save the JSON string to a file from PHP and then load the contents of the file in Python, deleting the file afterwards if necessary.

I've found an elegant solution, hope it can be useful for anyone:

PHP file:

<p>Test JSON</p>
<?php
$loc = "Roma Sud";
$hotel = array("Name"=>$loc,"Stars"=>"3");
$param = base64_encode(json_encode($hotel));
$result = shell_exec("/var/www/html/test-json/test.py $param");
// echo "<strong>Hotel Name: </strong>";
$obj = json_decode($result);
print "<strong>Hotel Name: </strong>" . $obj->Name . "<br/>";
print "<strong>Stars: </strong>" . $obj->Stars . "<br/>";
?>

Python file:

#!/usr/bin/env python
import sys
import json
import base64
    
content = json.loads(base64.b64decode(sys.argv[1]))
print(json.dumps(content))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM