Send json array in post request php

The problem your having is this string is NOT Proper JSON: [500,'hello world']

this would be proper JSON [500,"hello world"]. JSON is very strict on formatting and requires that all string values be wrapped in double quotes and NEVER single quotes.

the proper thing to do to avoid problems, would be to use the php functions json_encode() and json_decode()

for example,


and in the post.php you would read it like so,


the true flag in json_decode() tells the function you want it as an associative array and not a PHP object, which is its default behavior.

the print_r() function will output the php structure of the converted JSON array:

Array(
    [0] => 500
    [1] => hello world
) 

In this guide, we are going to show you how to send JSON data in PHP.

In certain cases, you will come across web services and APIs that will require you to send JSON via a POST request.

The easiest way to achieve this is by using PHP’s cURL functions.

Take a look at the following example.

//The URL of the API.
$url = 'http://example.com/api/JSON/create';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

In the code above, we did the following.

  1. We specified the URL that we want to send our JSON to. This is usually the URL of the API that we want to send the data to.
  2. After that, we initiated cURL by using the curl_init function.
  3. Then, we setup a PHP array containing sample data.
  4. We encoded our PHP array into a JSON string by using the function json_encode.
  5. We when told cURL that we want to send a POST request by setting the CURLOPT_POST option to 1.
  6. After that, we attached our JSON data by using the CURLOPT_POSTFIELDS option.
  7. We then set the content-type of our request to application/json using the CURLOPT_HTTPHEADER option. It is extremely important to note that you should always use “application/json”, not “text/json”. Simply put, using “text/json” is incorrect and may lead to errors!
  8. Finally, we use the function curl_exec to execute our POST request. If you want to check for errors at this stage, then you should check out our article on error handling with cURL.

As you can see, it’s not much different than sending a regular POST request. In fact, the only real difference is that we set the content type to application/json.

Related: How to retrieve raw JSON POST data with PHP.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features:

    • php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type.
    • file_get_contents() function: This function in PHP is used to read a file into a string.
    • json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.

    It is known that all of the post data can be received in a PHP script using the $_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

    Handling JSON POST requests:

    // Takes raw data from the request
    $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
    $data = json_decode($json);

    Example 1: This example uses the json_decode() function that is used to decode a JSON string.

    PHP

      $json = '["geeks", "for", "geeks"]';

      $data = json_decode($json);

      echo $data[0];

    ?>

    Example 2: This example uses the json_decode() function that is used to decode a JSON string.

    PHP

      $json = '{

          "title": "PHP",

          "site": "GeeksforGeeks"

      }';

      $data = json_decode($json);

      echo $data->title;

      echo "\n";

      echo $data->site;

    ?>

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


    How do I give JSON data to postman?

    POST requests In Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.

    How to process JSON data in PHP?

    PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.

    How to get JSON response from rest API in PHP?

    To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

    How are JSON values accessed in PHP?

    PHP and JSON.
    The json_encode() function is used to encode a value to JSON format..
    The json_decode() function is used to decode a JSON object into a PHP object or an associative array..
    The json_decode() function returns an object by default. ... .
    You can also loop through the values with a foreach() loop:.