1

I'm trying to post some JSON data in PHP on my local server. I have the following code below but it's not working. Did i miss a vital thing?

<?php

 $postRequest = array ( 
      
    // Every array will be converted 
    // to an object 
       array( 
        "Attribute" => "FirstName", 
        "Value" => "maheshr"
    ),
       array( 
        "Attribute" => "LastName", 
        "Value" => "netha"
    ),array( 
        "Attribute" => "EmailAddress", 
        "Value" => "mahesh3@simandhareducation.com"
    ),array( 
        "Attribute" => "Phone", 
        "Value" => "9553754571"
    ),
    array( 
        "Attribute" => "Source", 
        "Value" => "Website"
    ), 
    array( 
        "Attribute" => "SearchBy", 
        "Value" => "Phone"
    ), 
    array( 
        "Attribute" => "mx_City", 
        "Value" => "Hyderabad"
    ) , 
    array( 
        "Attribute" => "mx_Course", 
        "Value" => "CPA"
    )
);

$postRequest = json_encode($postRequest);
// echo $postRequest;

$cURLConnection = curl_init('url');

curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postRequest);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
// $apiResponse - available data from the API request
$jsonArrayResponse = json_decode($apiResponse);
echo $jsonArrayResponse;

?>

I am not able to get any response from the curl request. Can anybody help me ?

Thank you.

Srikanth86in
  • 107
  • 2
  • 12
  • 1
    _“I am not able to get any response from the curl request.”_ - you did not actually check what response you got, so do that first of all. Don’t naively assume that what you got back, _must_ be valid JSON, and therefor be decodable as such. – 04FS Oct 01 '20 at 08:42
  • I have checked the developer tools and did not find any response for the request i send to the server – Srikanth86in Oct 01 '20 at 09:04
  • What developer tools are you talking about - browser? Pointless, you are making a request _from_ the server side. And that was not even what I was talking about to begin with - check what `$apiResponse` actually contains. – 04FS Oct 01 '20 at 09:07

1 Answers1

0

To post JSON data, you setup header before call curl_exec() like this:

curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
    ));

You can reference here : How to POST JSON Data With PHP cURL?

caocon912
  • 26
  • 6