如何在json中使用@访问索引

时间:2016-11-25 13:20:22

标签: php json xml laravel-5

我需要从这个" @ attributes"

获取属性
{
  "@attributes": {
    "docid": "1082530207018916577"
  },
  "track": [
    {
      "@attributes": {
        "id": "0",
        "name": "",
        "lang_code": "da",
        "lang_original": "Dansk",
        "lang_translated": "Danish"
      }
    },
    {
      "@attributes": {
        "id": "5",
        "name": "",
        "lang_code": "nl-BE",
        "lang_original": "Nederlands (België)",
        "lang_translated": "Dutch (Belgium)"
      }
    },
    {
      "@attributes": {
        "id": "2",
        "name": "",
        "lang_code": "en-GB",
        "lang_original": "English (United Kingdom)",
        "lang_translated": "English (United Kingdom)",
        "lang_default": "true"
      }
    },
    {
      "@attributes": {
        "id": "1",
        "name": "",
        "lang_code": "de-DE",
        "lang_original": "Deutsch (Deutschland)",
        "lang_translated": "German (Germany)"
      }
    },
    {
      "@attributes": {
        "id": "4",
        "name": "",
        "lang_code": "id",
        "lang_original": "Indonesia",
        "lang_translated": "Indonesian"
      }
    },
    {
      "@attributes": {
        "id": "6",
        "name": "",
        "lang_code": "pl",
        "lang_original": "Polski",
        "lang_translated": "Polish"
      }
    },
    {
      "@attributes": {
        "id": "7",
        "name": "",
        "lang_code": "pt-BR",
        "lang_original": "Português (Brasil)",
        "lang_translated": "Portuguese (Brazil)"
      }
    },
    {
      "@attributes": {
        "id": "3",
        "name": "",
        "lang_code": "es-419",
        "lang_original": "Español (Latinoamérica)",
        "lang_translated": "Spanish (Latin America)"
      }
    },
    {
      "@attributes": {
        "id": "8",
        "name": "",
        "lang_code": "sv",
        "lang_original": "Svenska",
        "lang_translated": "Swedish"
      }
    }
  ]
}

我的代码:

$xml = simplexml_load_file('http://video.google.com/timedtext?type=list&v='.$video->id_youtube);
$json = json_encode($xml);
$result_array = json_decode($json, TRUE);
$res = "";
foreach ($result_array['track']['@attributes'] as $track) {
    $res .= $track['lang_code'].'<br>';
}
return $res;

PHP或者Laravel无法识别索引&#34; @ attributes&#34;,报告:

  

未定义的索引:@attributes

如何获取 lang_codes

1 个答案:

答案 0 :(得分:3)

$ result_array ['track']是一个对象数组。

你必须做

foreach($result_array['track'] as $track) {
    $track = (array)$track;
    $res .= $track['@attributes']['lang_code'].'<br>';
}