如何在PHP中格式化JSON响应?

时间:2016-01-07 18:43:20

标签: php json

如何格式化此JSON响应以仅返回"结果"。它是卷曲响应的返回值。这是一个返回的完整字符串。

HTTP/1.0200OKCache-Control: no-cacheContent-Type: application/jsonDate: Thu,
07Jan201618: 33: 12GMT{
  "meta": {
    "code": 200
  },
  "**results**": {
    "national": {
      "goal_completions": 199,
      "sessions": 16251,
      "page_views": 23315,
      "users": 15691,
      "bounce_rate": 18.4784625
    },
    "regions": [
      {
        "region_id": 31,
        "region_name": "South",
        "data": {
          "ga_site_id": null,
          "goal_completions": null,
          "users": null,
          "sessions": null,
          "page_views": null,
          "bounce_rate": null
        }
      },
      {
        "region_id": 10,
        "region_name": "West",
        "data": {
          "ga_site_id": "4",
          "goal_completions": "199",
          "users": "15691",
          "sessions": "16251",
          "page_views": "23315",
          "bounce_rate": "73.91385000"
        }
      },
      {
        "region_id": 35,
        "region_name": "Northeast",
        "data": {
          "ga_site_id": null,
          "goal_completions": null,
          "users": null,
          "sessions": null,
          "page_views": null,
          "bounce_rate": null
        }
      },
      {
        "region_id": 36,
        "region_name": "Midwest",
        "data": {
          "ga_site_id": null,
          "goal_completions": null,
          "users": null,
          "sessions": null,
          "page_views": null,
          "bounce_rate": null
        }
      }
    ]
  }
}

感谢。

1 个答案:

答案 0 :(得分:1)

因此,在PHP中,您希望在输出中使用json_decode()函数,如下所示:

$jsonDecode = json_decode($response);
$onlyResults = $jsonDecode->results;

然后您可以使用它来收集或循环遍历对象的其余部分。

我建议关闭CURL响应标头:

set CURLOPT_HEADER to false.