Passing a JSON between PHP and Python

Viewed 17

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

1 Answers

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.

Related