Timo
Timo

Reputation: 107

PHP Api Receiving JSON data

I am trying to make an API with PHP and JSON, however I am stuck on extracting the JSON on the receiving/API side of the request.

So I am doing this on the client end of my transaction:

$data = array("test" => "test");                                                                    
$data_string = json_encode($data);
$ch = curl_init('https://..../api/v1/functions?  key=TPO4X2yCobCJ633&aid=9&action=add');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$return = curl_exec($ch);

But how do I receive and extract the POSTed data on the server (receiving) side of the transaction (inside my API)?

Summary:

What i mean is i have a client that is sending a JSON file to the API now i what i don't understand is how can i get the API side to see and extract/see the data

Upvotes: 5

Views: 4106

Answers (1)

JAAulde
JAAulde

Reputation: 19550

On the receiving side you need to read from the PHP input stream, then decode:

<?php

// read the incoming POST body (the JSON)
$input = file_get_contents('php://input');

// decode/unserialize it back into a PHP data structure
$data = json_decode($input);

// $data is now the same thing it was line 1 of your given sample code

If you wanted to be more succinct, you could obviously just nest those calls:

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

Upvotes: 5

Related Questions