?> Sending and Receiving JSON via POST

Sending and Receiving JSON via POST

In this example we will looking at how to create a JSON array and then send the JSON via HTTP POST. We will be using cURL as the method of sending the data. In the second half of the example, I will explain how to retrieve the JSON that has been sent and then manipluate the data for a specific purpose.

Sending JSON via POST

  $jsonArray = array( 
"name" => array(
"firstname" => "John",
"surname" => "Smith"
),
"age" => "30",
"dob" => "20/02/1987",
"address" => "1 Skipton Road, Cheshire",
"postcode" => "CH1 SK6"
)
);

$json = json_encode($jsonArray);

Here we are creating our JSON by specifiying the values in which we require within an associative array. The array can be a multidimensional array and contain as many Key => Values as you require. Once the array has been set up, we then use json_encode() to encode the php array into JSON.


  { "json" : [ {
"name": {"firstname": John, "surname": Smith}
"age" : 30,
"dob" : "20/02/1987",
"address" : "1 Skipton Road, Cheshire",
"postcode" : "CH1 SK6" ]}
}

This is this the resulted JSON from out encoded array above.


  $url = 'http://www.example.com';
$url = curl_init($url);
curl_setopt($url, CURLOPT_POST, 1);
curl_setopt($url, CURLOPT_POSTFIELDS, $json);
curl_setopt($url, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($url);

cURL is used for transferring the data. First of all we specify the location in which the JSON needs to be sent in the $url vairable. The CURLOPT_POST option turns on HTTP POST and the CURLOPT_POSTFIELDS option contains our JSON array. We then set CURLOPT_HTTPHEADER so the server knows we are sending JSON.


Receiving JSON

  $input = file_get_contents("php://input");
$json = json_decode($input, true);

Using file_get_contents() is the preferred way to read the contents of a file into a string. You can specify a specific file name, such as 'www.example.com/data' or use "php://input" to read any input sent to the page.

json_decode() is then used to decode the JSON string. The second aprameter is set to true, which converts returned objects into associative arrays.


  if(!empty($json)){	
for($i=0; $i < count($json); $i++) {
$firstName = $json['name']['firstname'];
$surName = $json['name']['surname'];
$age = $json['age'];
$dob = $json['dob'];
$address = $json['address'];
$postCode = $json['postcode'];
}
}

Once the JSON string has been decoded, you can then manipluate the data however you see fit. In this example we are using a for loop in order to loop through the JSON and pick out the individual array values. The data can then be inserted into a database or any other action it's required for.

Top