php中怎么定义json变量,如何在JSON请求体中使用php变量?

我有一个请求正文如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值