PHP解析TypeForm JSON Post数据失败,请求提取指定字段
解决TypeForm Webhook JSON数据提取问题
别担心,基础问题完全没问题!你的代码之所以返回null,是因为没找对JSON数据的层级——text和label根本不在根节点上,而是藏在form_response下的answers数组里,咱们一步步来修复:
先搞懂JSON的结构
你收到的JSON核心层级是这样的:
根对象 →
form_response→answers(数组,每个元素对应一个表单字段的回答)
- 第一个回答对象:
type: "text"→ 包含text: "250252"- 第二个回答对象:
type: "choice"→ 嵌套在choice里的label: "CE"
方法1:按数组索引直接提取(简单但依赖字段顺序)
如果你的表单字段顺序固定,直接按数组位置取就行:
// 解码JSON,第二个参数设为true转成关联数组(用对象也可以,语法稍改) $data = json_decode(file_get_contents('php://input'), true); // 提取ID(第一个回答的text) $ID = $data['form_response']['answers'][0]['text']; // 提取技能(第二个回答的choice->label) $Skill = $data['form_response']['answers'][1]['choice']['label']; // 测试输出 var_dump($ID, $Skill);
如果习惯用对象操作,代码改成这样:
$data = json_decode(file_get_contents('php://input')); $ID = $data->form_response->answers[0]->text; $Skill = $data->form_response->answers[1]->choice->label; var_dump($ID, $Skill);
方法2:遍历数组匹配字段(更健壮,不怕字段顺序变化)
如果以后表单字段顺序可能调整,建议通过字段的id或type来匹配,避免出错:
$data = json_decode(file_get_contents('php://input'), true); $answers = $data['form_response']['answers']; $ID = ''; $Skill = ''; // 遍历所有回答,根据字段ID匹配(最精准) foreach ($answers as $answer) { // 匹配ID输入框的字段ID if ($answer['field']['id'] === 'kUbaN0JdLDz8') { $ID = $answer['text']; } // 匹配技能选择框的字段ID elseif ($answer['field']['id'] === 'JQD4ksDpjlln') { $Skill = $answer['choice']['label']; } } // 或者按字段类型匹配(适合同类型字段唯一的情况) // foreach ($answers as $answer) { // if ($answer['field']['type'] === 'short_text') { // $ID = $answer['text']; // } elseif ($answer['field']['type'] === 'multiple_choice') { // $Skill = $answer['choice']['label']; // } // } var_dump($ID, $Skill);
为什么原来的代码失效?
你之前写的$data->{"text"}是直接从根对象找text属性,但根对象里只有event_id、event_type、form_response这几个属性,根本没有text和label,所以自然返回null啦。
内容的提问来源于stack exchange,提问作者Nips
相关产品推荐
相关产品推荐

