Search code examples
phpjsontypeform

JSON Post PHP (TypeForm)


I have never used JSON before so apologies if this is a simple request.

I have a webhook setup that sends me a JSON Post (Example Below) - I want to extract the two answers from this "text":"250252" & {"label":"CE"}

{
  "event_id": "1",
  "event_type": "form_response",
  "form_response": {
    "form_id": "VpWTMQ",
    "token": "1",
    "submitted_at": "2018-05-22T14:11:56Z",
    "definition": {
      "id": "VpWTMQ",
      "title": "SS - Skill Change",
      "fields": [
        {
          "id": "kUbaN0JdLDz8",
          "title": "Please enter your ID",
          "type": "short_text",
          "ref": "9ac66945-899b-448d-859f-70562310ee5d",
          "allow_multiple_selections": false,
          "allow_other_choice": false
        },
        {
          "id": "JQD4ksDpjlln",
          "title": "Please select the skill required",
          "type": "multiple_choice",
          "ref": "a24e6b58-f388-4ea9-9853-75f69e5ca337",
          "allow_multiple_selections": false,
          "allow_other_choice": false
        }
      ]
    },
    "answers": [
      {
        "type": "text",
        "text": "250252",
        "field": {
          "id": "kUbaN0JdLDz8",
          "type": "short_text"
        }
      },
      {
        "type": "choice",
        "choice": {
          "label": "CE"
        },
        "field": {
          "id": "JQD4ksDpjlln",
          "type": "multiple_choice"
        }
      }
    ]
  }
}

I have this currently in my PHP file:

$data = json_decode(file_get_contents('php://input'));
$ID = $data->{"text"};
$Skill = $data->{"label"};

This does not work and all I get is null - Any help would really be appreciated, Thank You.


Solution

  • You need to look at the JSON object you're receiving to know the structure of the object you're receiving after using json_decode, what you're trying to get is in $data->form_response->answers, So you can have a variable for easier access:

    $answers = $data->form_response->answers;
    

    remember $answers is an array

    So to achieve what you're trying to get, you can do:

    $data = json_decode(file_get_contents('php://input'));
    $answers = $data->form_response->answers;
    $ID = $answers[0]->text;
    $Skill = $answers[1]->choice->label;