Skip to content
Advertisement

php json parse access child values

I’m trying to filter and later access to the child data of a nested json file using PHP but for now i’m unable to do it.

Json example:

{ "_embedded": {
        "items": [
            {
                "uuid": "zL7j58B5fC3",
                "dns_records": [
                    {
                        "type": "TXT",
                        "name": "_amazonses1.test.com"
                    },
                    {
                        "type": "TXT",
                        "name": "_ddplatform1.test.com"
                    }    
                ]
            },
            {
                "uuid": "Zf6Yr2n07",
                "dns_records": [
                    {
                        "type": "TXT",
                        "name": "_amazonses2.test.com",
                    },
                    {
                        "type": "TXT",
                        "name": "_ddplatform2.test.com"
                    }
                ],
            }
        ]
    }
}

I’ve tried with this code:

$data = json_decode($resp, true);
if( ! empty( $data ) ) {
    foreach($data['_embedded']['items'] as $item){
      if($item['uuid'] == $domain_id){
          $dns_entries=$item['uuid']['dns_records']['name'];
     } else {
          $dns_entries = '';
     }
      echo $dns_entries;
}

So $domain_id is an external value that I passed through the function. The idea is that if it matches one of the child’s values, then I can extract the values inside that child.

If I pass $domain_id as Zf6Yr2n07 then I need to extract the TXT information (name) inside that child node. e.g. _amazonses2.test.com

Any tip will be highly appreciated.

Advertisement

Answer

First, your JSON is invalid. Make sure to remove trailing commas.

Second, you’re accessing $item["uuid"]["dns_records"]["name"], but

  1. dns_records is an array
  2. dns_records exists on $item, not $item["uuid"]

To get only the first name, just select the first element inside the dns_records array: $item["dns_records"][0]["name"]

Another option is to return an array with all the available names by looping through all child elements of dns_records and pushing the name to a new array:

if( ! empty( $data ) ) {
    $dns_entries = [];
    foreach($data['_embedded']['items'] as $item){
        if($item['uuid'] == $domain_id){
            foreach($item['dns_records'] as $dns_item) {
                $dns_entries[] = $dns_item["name"];
            }
        }
    }
    print_r($dns_entries); // print_r because echo doesn't work with arrays
}

Live demo on onlinephp.io

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement