I have a list of emails and want to extract each email's domains names and the DNS_MX for each domain. Here's the code I have:
<?php
$emaillist = file('list.txt');
foreach ($emaillist as $x) {
$domain = substr(strrchr($x, "@"), 1);
$mx = dns_get_record($domain, DNS_MX);
foreach ($mx as $key1) {
$mxtarget = $key1['target'];
}
echo "$mxtarget <br>";
}
?>
Problem: When I echo $mxtarget, it echoes only the value of the last email on the list but doesn't echo the list of the emails before it. However, if I echo domain, it echoes the domains for all the emails on the list.
Your echo
statement is outside your foreach
loop. Placing the echo
inside the inner loop will echo each MX one at a time.
If you'd rather echo them all at once with a single command, collect them in a variable inside the loop and then echo the whole list.
Edit:
In order to process your text file as it's currently formatted, you'll need to first remove the line breaks from each element in the array.
<?php
$emaillist = file('https://cardguard.xyz/tools/list.txt');
foreach ($emaillist as &$email) {
$email = str_replace(array("\r", "\n"), '', $email);
}
foreach ($emaillist as $x) {
$domain = substr(strrchr($x, "@"), 1);
$mx = dns_get_record($domain, DNS_MX);
//$mxtarget = "";
foreach ($mx as $key1) {
$mxtarget = $key1['target'];
echo "$mxtarget. \n";
}
}
?>