Sending JSON DATA with PHP cURL
Sometimes APIs
wants you to send json data. in such cases cURL
we need to make some additions to post operations with cURL.
The relevant code can be found below.
Also the technique of taking in the posted place is a little bit different, you can find it in part 2.
<?php
$data = array("name" => "phpExample", "age" => "27");
$data_string = json_encode($data);
$ch = curl_init('http://localhost/xxx.php');
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))
);
$result = curl_exec($ch);
echo $result;
In xxx.php that we made the request we are taking the json data a little different than taking with $_POST
. That way is this;
$posts = file_get_contents('php://input');
$jsonData = json_decode($posts, true);
print_r($jsonData);
Comments
Popular Articles
Popular Tags
- #directive
- #Function
- #Json
- #Class
- #SASS
- #Form
- #Redirect
- #API
- #Special Characters
- #Special
- #Random
- #Generating
- #
- #Text
- #Ajax
- #URL
- #Encrypting
- #React
- #Show
- #timeAgo
- #PSR-4
- #Hide
- #DDOS Protection
- #DDOS
- #cURL
- #Logic For Displaying Posts
- #Error
- #Key
- #General Error
- #1364 Field
- #Abbreviation
- #Blade
- #Version
- #QR
- #QR Code Generating
- #Array
- #Arrays with Key Values to String Statement
- #Short Tag
- #Activate
- #Real Time
- #Socket.io
- #301
- #Custom Directives
- #Iframe Detection
- #Date
- #Characters
- #Insert
- #Autoloader
- #Composer
- #Reading
There are no comments, make the firs comment