我有一个请求正文如下:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"username\":\"testuser5@so.com\",\"send_welcome\":true,\"welcome_message\":\"Test\",\"account_attributes\":{\"email_address\":\"testuser5@so.com\",\"first_name\":\"Snow\",\"last_name\":\"White\",\"middle_initial\":\"A\",\"phone_number\":\"2055551234\",\"address\":\"1 Main St\",\"city\":\"Detroit\",\"state\":\"MI\",\"zip\":\"48220\",\"country\":\"US\"},\"Gender\":\"Male\",\"portals\":[],\"groups\":[],\"identification_card_numbers\":[]}");
我想将用户名php变量分配给“username”json参数,但是当我尝试时,我仍然会导致400个错误请求:
$username = json_encode('something@something.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"username\":" . $username . ",\"send_welcome\":true,\"welcome_message\":\"Test\",\"account_attributes\":{\"email_address\":\"testuser5@so.com\",\"first_name\":\"Snow\",\"last_name\":\"White\",\"middle_initial\":\"A\",\"phone_number\":\"2055551234\",\"address\":\"1 Main St\",\"city\":\"Detroit\",\"state\":\"MI\",\"zip\":\"48220\",\"country\":\"US\"},\"Gender\":\"Male\",\"portals\":[],\"groups\":[],\"identification_card_numbers\":[]}");
解决方法:
尝试:
$username = 'test@gmail.com';
$json = json_encode(
array(
"username" => $username,
"send_welcome" => true,
"welcome_message" => "Test",
"account_attributes" => array(
"email_address" => "testuser5@so.com",
"first_name" => "Snow",
"last_name" => "White",
"middle_initial" => "A",
"phone_number" => "2055551234",
"address" => "1 Main St",
"city" => "Detroit",
"state" => "MI",
"zip" => "48220",
"country" => "US"
),
"Gender" => "Male",
"portals" => [],
"groups" => [],
"identification_card_numbers" => []
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
使用数组并使用json_encode()来获取JSON
为什么?
PHP不能像Javascript那样自然地使用JSON,并且使用原始字符串连接和构造JSON是一种不好的做法并且很头疼.
标签:json,php
来源: https://codeday.me/bug/20190716/1474310.html