简体   繁体   中英

How to get data from an array inside json data php

I have the following array of json data. When I try to loop using a for each, php gives me the error "Object of class stdClass could not be converted to string". I want to access the nameserver in the authns array, and the soa array. How do I go about doing that?

stdClass Object ( 
    [error] => 
    [domain] => whoisdoma.net 
    [ip_address] => 108.162.199.120   
    [authns] => stdClass Object ( 
        [nameserver] => uma.ns.cloudflare.com 
        [ip] => 173.245.58.146 
        [location] => San Francisco 
    ) 
    [soa] => stdClass Object ( 
        [nameserver] => tom.ns.cloudflare.com 
        [email] => dns.cloudflare.com 
        [serial] => 2015505396 
        [refresh] => 10000 
        [retry] => 2400 
        [expiry] => 604800 
        [minimum] => 3600 
    )
) 

This is the code I'm using to get the data:

 <?php
 $domain = $_GET['domain'];
//set the url
$url = "http://api.site.ga/v1/dns/lookup?domain=".$domain;

//start a curl session
$ch = curl_init();
$timeout = 5;

//set curl options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

//get the data
$data = curl_exec($ch);

//decode the data
$jsonData = json_decode($data);

//close the curl session
curl_close($ch);

?>

This is the for each loop I'm using

<?php 

foreach($jsonData->authns as $authns)
{
    echo $authns->nameserver;
}

?>

You need to decode the json object using an associative array.

Here is an exmaple:

$data = json_decode(file_get_contents('http://api.domain.com/call'), true);

$data is now an associative array.

You are looping through authns while it is an object by itself. So your nameserver which you want is actually $authns in its first iteration.

Just access it like $jsonData->authns->nameserver

try this for yourself

foreach($jsonData->authns as $authns)
{
    echo $authns;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM