How to POST JSON Data With PHP cURL?

前端 未结 7 2269
失恋的感觉
失恋的感觉 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:20

    Replace

    curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string));
    

    with:

    $data_string = json_encode(array("customer"=>$data));
    //Send blindly the json-encoded string.
    //The server, IMO, expects the body of the HTTP request to be in JSON
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    

    I dont get what you meant by "other page", I hope it is the page at: 'url_to_post'. If that page is written in PHP, the JSON you just posted above will be read in the below way:

    $jsonStr = file_get_contents("php://input"); //read the HTTP body.
    $json = json_decode($jsonStr);
    

提交回复
热议问题