You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress端点接收Guzzle发送的数组类型POST请求?

嘿,我来帮你搞定这个数组参数处理的问题!首先咱们先把发送端的代码调整成能发送数组的样子,再一步步讲WordPress接收端怎么处理。

第一步:调整Guzzle发送数组参数

你现在的测试代码发送的都是单个键值对,要发送数组的话,只需要在form_params里嵌套数组就行,比如:

$client = new Client();
$response = $client->request('POST', 'http://httpbin.org/post', [
    'form_params' => [
        'email' => 'test@gmail.com',
        // 这里是要发送的数组参数
        'user_profile' => [
            'name' => 'Test user',
            'age' => 30,
            'hobbies' => ['reading', 'coding']
        ],
        'password' => 'testpassword',
    ],
    'debug' => true
]);
echo '<pre>' . print_r((string)$response->getBody(), true) . '</pre>';

运行这段代码后,你会看到httpbin返回的form字段里,数组参数会以user_profile[name]、user_profile[hobbies][0]这种格式展示——PHP会自动把这种格式解析成关联数组,所以接收端直接拿就行。

第二步:WordPress接收端处理数组参数

在WordPress的接收端点(比如自定义的API接口或者模板文件里),你可以这样处理数组:

1. 先判断数组是否存在且有效

和单个参数的isset判断类似,但要额外确认是数组类型,避免后续操作报错:

// 先检查数组参数是否存在,并且是合法数组
if (isset($_POST['user_profile']) && is_array($_POST['user_profile'])) {
    $userProfile = $_POST['user_profile'];
    
    // 接下来就可以像操作普通PHP数组一样处理了
}

2. 读取数组里的子元素

比如要获取用户名、年龄,或者遍历爱好列表:

if (isset($_POST['user_profile']) && is_array($_POST['user_profile'])) {
    $userProfile = $_POST['user_profile'];
    
    // 获取单个子元素(记得用WordPress的 sanitize 函数过滤输入,防止安全问题)
    $userName = isset($userProfile['name']) ? sanitize_text_field($userProfile['name']) : '匿名用户';
    $userAge = isset($userProfile['age']) ? absint($userProfile['age']) : 0;
    
    echo "用户名:{$userName}<br>";
    echo "年龄:{$userAge}<br>";
    
    // 处理多维数组(比如爱好列表)
    if (isset($userProfile['hobbies']) && is_array($userProfile['hobbies'])) {
        echo "爱好:";
        foreach ($userProfile['hobbies'] as $hobby) {
            echo sanitize_text_field($hobby) . " ";
        }
    }
}

3. 更安全的获取方式(推荐)

WordPress里推荐用filter_input函数来获取POST数据,它能帮你更安全地验证和过滤数组:

// 用filter_input获取数组,FILTER_REQUIRE_ARRAY确保返回的是数组
$userProfile = filter_input(INPUT_POST, 'user_profile', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

if ($userProfile) {
    // 这里处理数组,同样记得用sanitize函数过滤子元素
    $userName = sanitize_text_field($userProfile['name'] ?? '匿名用户');
    // ...其他处理
}

关键点提醒

  • 发送端的数组嵌套层级没有限制,只要接收端对应判断层级就行;
  • 一定要对用户输入做过滤(比如sanitize_text_field、absint),这是WordPress开发的安全最佳实践,能防止XSS攻击和恶意数据;
  • 如果你用httpbin测试,先确认返回的form数据里包含你的数组,再到WordPress端调试,这样能先排除发送端的问题。

内容的提问来源于stack exchange,提问作者Desory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:35:01