将表单 PHP 变量传递给 JSON 编码

Pass Form PHP Variables to JSON Encode

我有一个包含这些值的表单:

    $firstName = strip_tags(trim($_POST['first-name']));
    $lastName = strip_tags(trim($_POST['last-name']));
    $email = filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL);

我正在尝试将这些值传递给它:

    $request_body = json_decode('[{
        "first_name" : "Tom",
        "last_name" : "Hanks",
        "email" : "example@gmail.com"
    }]');

尝试将表单值保存到数组并将其传递到 json_decode,其中 $userArray 是表单值,但没有成功。示例:

$request_body = json_decode($userArray, true);

所有这些都是为了将​​这些表单值传递到 API (SendGrid),但它对我不起作用,而且他们的文档描述性不强。我猜他们想要一个特定的请求格式。这是来自他们的 Github 页面的请求正文示例。我可以将这些值硬编码进去并且工作正常,但我的想法是让表单自动传递这些用户名和电子邮件值。

$request_body = json_decode('[
  {
    "age": 25, 
    "email": "example@example.com", 
    "first_name": "", 
    "last_name": "User"
  }, 
  {
    "age": 25, 
    "email": "example2@example.com", 
    "first_name": "Example", 
    "last_name": "User"
  }
]');

知道我做错了什么吗?谢谢!

我认为您在使用 json_decode()json_encode() 时可能会有点困惑。

json_encode() 将 PHP 数组编码为 JSON 数组。 而 json_decode() 将 JSON 数组解码回 PHP 数组。

关于您的情况,以下应该产生相同的输出:

$array = array(
    "first_name" => "Tom",
    "last_name" => "Hanks",
    "email" => "example@gmail.com"
);

echo json_encode($array);

产生:

{"first_name":"Tom","last_name":"Hanks","email":"example@gmail.com"}

使用这些函数构建数组然后 encode/decode to/from JSON 比手动创建 JSON 数组要好得多。因为这可以避免您可能造成的任何语法错误。

希望对您有所帮助。

您发送 post 的方式:

$array[0]['email'] = filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL);
$array[0]['first_name'] = strip_tags(trim($_POST['first-name']));
$array[0]['last_name'] = strip_tags(trim($_POST['last-name']));

echo json_encode($array);

结果:

[{"email":"john.doe@exemple.com","first_name":"John","last_name":"Doe"}]

[0] 可能是个问题,它会在您读取 json_decode 输出时生成“[”“]”,并在使用 json_decode 解码时重现完全相同的数组。

因此,如果他们的脚本正在寻找整数作为键,如果您省略 [0],他们将获得以下格式的数组 $array['email'] 等。这可能是个问题。

如果您想循环重现并一次发送多个条目

你可以这样写:

$array[] = array('email' => filter_var(trim($_POST['user-email']),FILTER_SANITIZE_EMAIL),
                 'first_name' => strip_tags(trim($_POST['first-name'])),
                 'last_name' => strip_tags(trim($_POST['last-name']))
);

您仍然会错过 "age"。确保它不是必填字段!