How to get the .tld from an URL via PHP?
E.g. www.domain.com/site, the PHP should post: tld is: .com.
If you want extract host from string www.domain.com/site
, usage of parse_url() is acceptable solution for you.
But if you want extract domain or its parts, you need package that using Public Suffix List. Yes, you can use string functions around parse_url(), but it will produce incorrect results with two level TLDs.
I recommend TLDExtract [note: library has been deprecated in favour of the similar PHP Domain Parser] for domain parsing, here is sample code that show diff:
$extract = new LayerShifter\TLDExtract\Extract();
# For 'http://www.example.com/site'
$url = 'http://www.example.com/site';
parse_url($url, PHP_URL_HOST); // will return www.example.com
end(explode(".", parse_url($url, PHP_URL_HOST))); // will return com
$result = $extract->parse($url);
$result->getFullHost(); // will return 'www.example.com'
$result->getRegistrableDomain(); // will return 'example.com'
$result->getSuffix(); // will return 'com'
# For 'http://www.example.co.uk/site'
$url = 'http://www.example.co.uk/site';
parse_url($url, PHP_URL_HOST); // will return 'www.example.co.uk'
end(explode(".", parse_url($url, PHP_URL_HOST))); // will return uk, not co.uk
$result = $extract->parse($url);
$result->getFullHost(); // will return 'www.example.co.uk'
$result->getRegistrableDomain(); // will return 'example.co.uk'
$result->getSuffix(); // will return 'co.uk'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With