How to POST JSON Data With PHP cURL?

前端 未结 7 2201
失恋的感觉
失恋的感觉 2020-11-22 10:02

Here is my code,

$url = \'url_to_post\';
$data = array(
    \"first_name\" => \"First name\",
    \"last_name\" => \"last name\",
    \"email\"=>\"e         


        
相关标签:
7条回答
  • 2020-11-22 10:41

    Try like this:

    $url = 'url_to_post';
    // this is only part of the data you need to sen
    $customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"email@gmail.com","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
    // As per your API, the customer data should be structured this way
    $data = array("customer" => $customer_data);
    // And then encoded as a json string
    $data_string = json_encode($data);
    $ch=curl_init($url);
    
    curl_setopt_array($ch, array(
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_HEADER => true,
        CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
    ));
    
    $result = curl_exec($ch);
    curl_close($ch);
    

    The key thing you've forgotten was to json_encode your data. But you also may find it convenient to use curl_setopt_array to set all curl options at once by passing an array.

    0 讨论(0)
提交回复
热议问题