这是我得到的响应json。请帮助解析json。我使用json_decode,但我不知道如何处理不带名称的对象。
{
"child": {
"": {
"rss": [{
"data": "\n \n",
"attribs": {
"": {
"version": "2.0"
}
},
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": "",
"child": {
"": {
"channel": [{
"data": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ",
"attribs": [],
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": "",
"child": {
"": {
"title": [{
"data": "Data name",
"attribs": [],
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": ""
}]
}
}
}]
}
}
}]
}
}
}
我正在尝试获取title中数据的值。但是我不知道如何解决一个没有名字的对象。有人可以帮忙吗。
{
"child": {
"": {}}}
答案 0 :(得分:1)
这可能会有所帮助;
<?php
$json='{
"child": {
"": {
"rss": [{
"data": "\n \n",
"attribs": {
"": {
"version": "2.0"
}
},
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": "",
"child": {
"": {
"channel": [{
"data": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ",
"attribs": [],
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": "",
"child": {
"": {
"title": [{
"data": "Data name",
"attribs": [],
"xml_base": "",
"xml_base_explicit": false,
"xml_lang": ""
}]
}
}
}]
}
}
}]
}
}
}';
$json_decoded=json_decode($json,true);
print_r($json_decoded['child']['']);
?>
答案 1 :(得分:1)
有两种访问title
对象的方法,具体取决于您将JSON解码为对象还是数组。如果您将其解码为对象,则需要使用->{'element'}
表示法来避开空名称(注意,该仅在PHP 7.2及更高版本中有效):
$json = json_decode($jsonstr);
print_r($json->child->{''}->rss[0]->child->{''}->channel[0]->child->{''}->title);
输出:
Array (
[0] => stdClass Object (
[data] => Data name
[attribs] => Array ( )
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
)
作为一个数组,您只需要使用一个空白索引(''
):
$json = json_decode($jsonstr, true);
print_r($json['child']['']['rss'][0]['child']['']['channel'][0]['child']['']['title']);
输出:
Array (
[0] => Array (
[data] => Data name
[attribs] => Array ( )
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
)