Receive json data in PHP

Asked

Viewed 1,959 times

9

I’m having trouble receiving JSON data in PHP to save to the database, and this data is sent from a python script, have tried the json_decode using the variable $_REQUEST, but unsuccessfully, when I record in a .txt i can get the data but when I try to write to a variable to save to the database I can’t print anything to confirm that the data went to variable.

Python

import json
import requests
import Adafruit_DHT
import RPi.GPIO as GPIO
import Adafruit_BMP.BMP085 as BMP085
import time

sensorBMP = BMP085.BMP085();
sensorDHT11 = Adafruit_DHT.DHT11;

GPIO.setmode(GPIO.BOARD);
pinoSensorDHT11 = 25;

temperature = 0.0;
pressure = 0.0;
humidity = 0.0;
dia = 0;
hora = 0.0;

while(1):
temperature = sensorBMP.read_temperature();
pressure = sensorBMP.read_pressure();
altitude = sensorBMP.read_altitude();
dia = time.strftime("%d/%m/%Y");
hora = time.strftime("%H/%M/%S");
while(1):
humidity, tempNotUsed = Adafruit_DHT.read_retry(sensorDHT11,pinoSensorDHT11);
    if humidity is not None and tempNotUsed is not None:
        dic = {
            'Temperature' : temperature,
            'Humidity' : humidity,
            'Pressure' : pressure,
        }
        jason = json.dumps(dic);
        print(jason);


        r = requests.post("http://54.174.181.91/tcc/jsonTeste.php",   data = {"jsonFile": jason});

        #print (r);
        if r.status_code is not 200:
            print "FALHA!!!!!!";
            print r.status_code;
            break;
    break;
break;

And when write to txt using PHP:

<?php
echo "<pre>";
var_dump($_POST); 
$data = $_POST["jsonFile"];


// Abre ou cria o arquivo bloco1.txt
// "a" representa que o arquivo é aberto para ser escrito

$fp = fopen("bloco1.txt", "w");

// Escreve "exemplo de escrita" no bloco1.txt
$escreve = fwrite($fp, $data);

// Fecha o arquivo
fclose($fp);


?>

How can I take this data and write to a common variable?

  • If jsonFile is not present in $_POST the problem is in python that did not send the values.

  • But how does it record in txt? Because it records in txt but when I try to bring to some common variable I can not print on the screen, as it could solve?

  • When you do echo $data what appears?

  • Then you bring nothing :(

  • When vc displays the page source code (Ctrl+u) nothing appears? add these two lines at the beginning and see if any errors appear, ini_set('display_errors', true); error_reporting(E_ALL);

  • 1

    Here is the following: Notice: Undefined index: jsonFile in /var/www/html/tcc/jsonTeste.php on line 9

  • :Otimooo, a mistake, he says jsonFile was not sent. you did echo $_POST['jsonFile']; or echo $_GET['jsonFile'];

  • I think I did wrong, actually I did so: $data = $_POST["jsonFile"]; echo "test" . $data;

  • Do it like this and put the result here, echo '<pre>' print_r($_POST); print_r($_GET);

  • 1

    I did what you said but it brings 2 empty arrays: Array ( ) Array ( )

  • instead of writing to txt, save to.json and use json_encode for an array.

  • I think you are testing the wrong request. Do the following: In Python, after the line r = requests.post("htt... add print r.text In PHP, add only the line: print_r(json_decode($_POST['jsonFile'], true));

Show 7 more comments

4 answers

1

$_POST takes form data (headers of the kind urlencoded and form).

You will be able to get the data with

$data = json_decode(file_get_contents('php://input'));

reading the body of the request directly.

And why has this question now appeared on home ptSO after almost two years? OP failed to solve the problem in two years?

0

I didn’t quite understand the first doubt, that you can show how this json you’re trying to save would be easier.

But for your last doubt, when you save json in the file, serializes json before storing, because you would generate a serialized data and would be able to work better when picking up this file json, because when you read data from a file you can only read line by line. So you would take a single line that would have all your json data, would give a deserialize and could put into a single variable containing all its json.

To read files you can take a look at the php documentation. http://php.net/manual/en/function.file.php

  • Good morning Jose, so only that this txt was for testing to know if the data were sending to the page via $_POST, I don’t need txt only need the data to be written directly into a variable, for example: python’s 'Temperature' variable to be saved to a PHP $Temperature variable.

  • haaa, sacki, well, for this you have two ways, or you will have to create one (API, Webservice), to make the communication between the two languages that is most suitable, or make a post with python, that would be more complicated.

  • I understood José but if you look at Python I’m already sending via post, only that arrives in PHP and he can’t get the data

  • This project of yours is using Arduino? and is sending a post to a web page that uses php?

  • Talk Jose, that’s right, actually it’s a Raspberry.

  • Mass, like this, I didn’t stop to study it, but I’m also going to make just assumptions, It may be that Raspberry isn’t sending a correct json, on account of a botched lib. I didn’t dig too deep about Adian, but you may need an eternet shild to do the communication, I know eternet sends the correct http header as json, but if Raspberry already does this unfortunately I don’t have the possibility anymore :(

  • Do a favor to help answer, put this code in PHP and put the result here: &#xA; ob_start();&#xA; var_dump($_REQUEST);&#xA; var_dump($_SERVER);&#xA; $content = ob_get_clean();&#xA; file_put_contents("data.txt", $content);&#xA;

Show 2 more comments

-1

Since you are using Rduino it does not send the page header, you can use

header('Content-Type: application/json');
echo json_encode($data);

is one of the alternatives, the other is you set when saving in the bank the type of encoding this using, preferably UTF8

-2

Try it like this:

$data = json_decode($jsonFile);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.