php将Json解析为变量

时间:2017-03-28 13:52:34

标签: php json

我需要帮助使用php将json解析为变量。我用谷歌搜索并检查了很多howtos但没有成功。我认为问题在于我的json所处的格式。

这是json:

{&#34;类型&#34;:&#34;成功&#34;&#34;响应&#34; {&#34;数据&#34;:[{&#34; ID&#34 ;:5,&#34;用户名&#34;:&#34;帐户2&#34;&#34;主机名&#34;:&#34; testapp.net&#34;&#34;端口&#34; :8080&#34;状态&#34;:&#34;启用&#34;&#34;电子邮件&#34;:&#34; john@yourmomma.com",&#34; SERVERTYPE&#34 ;:&#34;的Icecast&#34;&#34; hostref&#34;:&#34; 0.0.0.0&#34;},{&#34; ID&#34:4,&#34;用户名& #34;:&#34;帐户1&#34;&#34;主机名&#34;:&#34; testapp2.net&#34;&#34;端口&#34;:8082,&#34;状态&# 34;:&#34;禁用&#34;&#34;电子邮件&#34;:&#34; john@yourmomma.com",&#34; SERVERTYPE&#34;:&#34; ShoutCast2&#34 ;,&#34; hostref&#34;:&#34; 0.0.0.0&#34;}],&#34;消息&#34;:&#34; 2个帐户&#34;}} < / p>

棘手的部分在&#34;响应&#34;之后开始。在哪里&#34;数据&#34;开始。

例如,我基本上需要将用户名,主机名和端口捕获到一个变量中,以便我可以稍后调用它,如果我想在另一个页面上显示它。

1 个答案:

答案 0 :(得分:0)

您需要使用json_decode()。该方法的完整文档可以在PHP Manual

中找到

从手册:

Takes a JSON encoded string and converts it into a PHP variable.

Returns the value encoded in json in appropriate PHP type. Values true,
false and null are returned as TRUE, FALSE and NULL respectively. NULL is 
returned if the json cannot be decoded or if the encoded data is deeper than 
the recursion limit.

我通常使用JSON Validator来测试json是否有效。在测试你的json时,它看起来没问题。您可能希望将json_decode()的第二个参数设置为true以激活关联处理(如果您还没有),以便所有结构都采用相同的格式。默认情况下,关联结构被解析为对象,这可能导致数据类型在有效负载的结构上发生变化。

在您的情况下,您将通过以下方式访问data部分中的一个变量:

$parsed = json_decode($string);
$id = $parsed->response->data[0]->id;

您在哪里使用了关联标志,您可以使用数组语法完全访问它:

$parsed = json_decode($string, true);
$id = $parsed['response']['data'][0]['id'];
相关问题