简体   繁体   中英

posting data using Curl in php

I have two array of objects that I want to post to an API but it displays an error missing value for parameter: productDC

it seems that i have to pass ProductDc and buyerDC along with their data. for this I also tried

 $data_string = array({ProductDc"product_name" => "Electronics","price" => "200 usd"},
    buyerDC{"buyer_name" => "john mark","address" => "17 more strret"}); 

below is the informations

1.) ProductDC pass it as array of objects **product_name(string)

price (string)**

2.) buyerDC pass it as array of objects **buyer_name(string)

address (string**)

here is my code

<?php

$data_string = array("product_name" => "Electronics","price" => "200 usd",
"buyer_name" => "john mark","address" => "17 more strret"); 


$data = json_encode($data_string); 
//$data = $data_string; 
$curl = curl_init();

curl_setopt_array($curl, array( 
CURLOPT_URL => "myapi.com", 
CURLOPT_RETURNTRANSFER => true, 
CURLOPT_ENCODING => "", 
CURLOPT_MAXREDIRS => 10, 
CURLOPT_TIMEOUT => 30, 
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
CURLOPT_CUSTOMREQUEST => "POST", 
CURLOPT_POSTFIELDS => "$data", 
CURLOPT_HTTPHEADER => array( 
"accept: application/json",  
"content-type: application/json; charset=utf-8" 
), 
));

$response = curl_exec($curl); 
$err = curl_error($curl);

curl_close($curl);

if ($err) { 
echo "cURL Error #:" . $err; 
} else { 
echo $response; 

}


?>

Considering below information that you have provided if they want a data in the format in which -

1.) ProductDC should be an array of objects containing -

product_name(string)

price (string)

2.) buyerDC should be array of objects containing-

buyer_name(string)

address (string)

Probably they are expecting the data in a different form which you may get by changing $data_string value as below -

$data_string = array(
                    "ProductDc"=>array(
                                    "product_name" => "Electronics",
                                    "price" => "200 usd"
                                ),

                    "buyerDC"=>array(
                                "buyer_name" => "john mark",
                                "address" => "17 more strret"
                              )
                ); 

Change your $data_string value to the one I posted above and check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM