Luiz Gonçalves Luiz Gonçalves - 10 days ago 6
JSON Question

How can I access index with @ in json

I need to get properties from this "@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"
}
}
]
}


My code:

$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 or maybe Laravel is not recognizing the index "@attributes", reporting:


Undefined index: @attributes


How can I get the lang_codes?

Answer

$result_array['track'] is an array of objects.

You have to do

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