问题
I want to return the nameservers of a domain in php, however I'm only getting one nameserver put in the array.
This is the code I am using:
//get auth ns datat
$authnsData = dns_get_record($domain, DNS_NS);
//put the results into a nice array
foreach ($authnsData as $nsinfo)
{
$authns = array(
'nsdata' => array(
'nameserver' => $nsinfo['target'],
'ip' => $this->getnsIP($nsinfo['target']),
'location' => $this->getipLocation($this->getnsIP($nsinfo['target'])),
),
);
return $authns;
}
The result I'm getting is:
Array
(
[nsdata] => Array
(
[nameserver] => ns-us.1and1-dns.org
[ip] => 217.160.83.2
[location] =>
)
)
Lets say a domain has 2 or more nameservers, I'm only getting one of those added to the array.
If you would like to test it out to find out the issue, the code is in this file: https://github.com/Whoisdoma/core/blob/master/src/Whoisdoma/Controllers/DNSWhoisController.php#L38
The function is getAuthNS, and LookupAuthNS. Before anyone suggests using a for loop, I have tried a for ($num = 0;) type loop.
回答1:
- You're returning too early, so that your loop only ever runs a single iteration.
- You're assigning a new array to
$authns
in every iteration, instead of pushing into it.
Try this piece of code instead:
foreach ($authnsData as $nsinfo)
{
$authns[] = [
'nsdata' => [
'nameserver' => $nsinfo['target'],
'ip' => $this->getnsIP($nsinfo['target']),
'location' => $this->getipLocation($this->getnsIP($nsinfo['target'])),
],
];
}
return $authns;
BTW, there's no need to run getnsIP
twice. You can use this instead:
foreach ($authnsData as $nsinfo)
{
$nameserver = $nsinfo['target'];
$ip = $this->getnsIP($nameserver);
$location = $this->getipLocation($ip);
$authns[] = ['nsdata' => compact('nameserver', 'ip', 'location')];
}
return $authns;
来源:https://stackoverflow.com/questions/24476786/returning-array-of-nameservers-for-domain-php