从嵌套的json php中获取价值

时间:2018-01-16 19:38:20

标签: php json

我正在接收来自webhook的数据,其中包含以下代码。

<?php
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

$myfile = fopen("callback.txt", "a") or die("Unable to open file!");

$txt = $input["payload"]["type"];

fwrite($myfile, "\n". $txt);


fclose($myfile);
http_response_code(200);
?>

我试图从重新调整的输出中获取'type'值。我发现在每个循环中使用if语句可以完成这项工作。但是我确信这不是一个理想的解决方案。是否有更直接的方式获得该元素?

上面的代码输出一个空文本文件。

并且文档显示json应采用以下格式:

{
  "action": "add",
  "collection": "broadcast",
  "payload": {
    "author": "Sveninge Bambuser",
    "created": 1474033783,
    "customData": "",
    "height": 540,
    "id": "9353eaec-794f-11e6-97c0-f19001529702",
    "ingestChannel": "cfc8626c-9a0e-ab78-6424-3eb0978d8e45",
    "lat": 63.205312,
    "length": 0,
    "lon": 17.13011,
    "positionAccuracy": 25,
    "positionType": "GPS",
    "preview": "https://archive.bambuser.com/9353eaec-794f-11e6-97c0-f19001529702.jpg",
    "resourceUri": "https://cdn.bambuser.net/broadcasts/9353eaec-794f-11e6-97c0-f19001529702?da_signature_method=HMAC-SHA256&da_id=9353eaec-794f-11e6-97c0-f19001529702&da_timestamp=1474033783&da_static=1&da_ttl=0&da_signature=eaf4c9cb29c58b910dcbad17cf7d8a3afa4e6a963624ba4c4fd0bb5bade1cdd6",
    "tags": [
      {
        "text": "whoa"
      }
    ],
    "title": "Amazing!",
    "type": "live",
    "width": 960
  },
  "eventId": "93df93061a891c23"
}

1 个答案:

答案 0 :(得分:0)

我换了:

$txt = $input["payload"]["type"];

使用:

$txt = $input['payload']['type'];

它似乎是导致问题的双引号。