Home >Backend Development >PHP Tutorial >How to Correctly POST JSON Data Using PHP cURL?

How to Correctly POST JSON Data Using PHP cURL?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 12:52:16520browse

How to Correctly POST JSON Data Using PHP cURL?

How to POST JSON Data With PHP cURL?

This question tackles the issue of posting JSON data using PHP's cURL library. The user provides a code snippet that aims to send POST data to a specific URL. However, the code fails to retrieve the posted data on the receiving page, resulting in an empty array.

Problem Details

The problem lies in the incorrect way the JSON data is being posted. Moreover, the code uses print_r($_POST) to retrieve the posted data, which is not the recommended method.

Solution

To correctly post JSON data using cURL, it is essential to ensure that the data is properly JSON-encoded. In the given code snippet, only the value of the "customer" POST field is JSON-encoded. Instead, the entire POST data should be JSON-encoded.

Additionally, to retrieve the posted data on the receiving page, you can utilize the file_get_contents("php://input") function, which will contain the posted JSON data.

Example Code

Here's an example of how to correctly post JSON data with PHP cURL:

<?php

$url = 'url_to_post';

$data = [
    "first_name" => "First name",
    "last_name" => "last name",
    "email" => "email@example.com",
    "addresses" => [
        "address1" => "some address",
        "city" => "city",
        "country" => "CA",
        "first_name" => "Mother",
        "last_name" => "Lastnameson",
        "phone" => "555-1212",
        "province" => "ON",
        "zip" => "123 ABC",
    ],
];

$data_string = json_encode($data);

$ch = curl_init($url);
# Setup request to send json via POST.
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
# Return response instead of printing.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# Send request.
$result = curl_exec($ch);
curl_close($ch);

# Print response.
echo "<pre class="brush:php;toolbar:false">$result
"; ?>

Note

Furthermore, the user expresses their intention to implement REST using JSON as per Shopify's API specifications. It is worth mentioning that using a third-party library specifically designed for interfacing with the Shopify API is highly recommended as it can simplify the process and reduce potential errors.

The above is the detailed content of How to Correctly POST JSON Data Using PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn