在php中使用Curl发布数据

问题描述 投票:0回答:1

我有两个对象数组,我想发布到API,但它显示参数:productDC的错误缺失值

似乎我必须传递ProductDc和buyerDC以及他们的数据。为此我也试过了

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

以下是信息

1.)ProductDC将其作为对象数组传递** product_name(string)

价格(字符串)**

2.)buyerDC将其作为对象数组传递** buyer_name(string)

地址(字符串**)

这是我的代码

<?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; 

}


?>
php curl
1个回答
1
投票

如果他们想要一种格式的数据,请考虑以下提供的信息 -

1.)ProductDC应该是一个包含的对象数组 -

PRODUCT_NAME(串)

价格(字符串)

2.)buyerDC应该是包含以下内容的对象数组:

BUYER_NAME(串)

地址(字符串)

可能他们期望通过更改$ data_string值得到不同形式的数据,如下所示 -

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

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

将$ data_string值更改为我上面发布的值并检查。

© www.soinside.com 2019 - 2024. All rights reserved.