php curl post json code example

Example 1: curl post json

curl -X POST -H "Content-Type: application/json" \
 -d '{"username":"abc","password":"abc"}' \
 https://api.example.com/v2/login

Example 2: php curl post

// set post fields
$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];

$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

// execute!
$response = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// do anything you want with your response
var_dump($response);

Example 3: curl post json

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

Example 4: post json array data curl

curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT -d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`

Example 5: how to do a post with json body curl php

// API URL$url = 'http://www.example.com/api';// Create a new cURL resource$ch = curl_init($url);// Setup request to send json via POST$data = array(    'username' => 'codexworld',    'password' => '123456');$payload = json_encode(array("user" => $data));// Attach encoded JSON string to the POST fieldscurl_setopt($ch, CURLOPT_POSTFIELDS, $payload);// Set the content type to application/jsoncurl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));// Return response instead of outputtingcurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Execute the POST request$result = curl_exec($ch);// Close cURL resourcecurl_close($ch);

Tags:

Php Example