How to Get the Top-Level Domain from a URL in PHP
It’s easy to get top-level domains from URL strings with a quick low-code API call in PHP.
To structure our API call, we can start by installing the PHP client via Composer. Let’s execute the below command from the command line:
composer require cloudmersive/cloudmersive_validate_api_client
Next, let’s grab a free Cloudmersive API key to authorize our API calls. These allow a limit of 800 API calls per month with no additional commitments.
With our API key ready to go, let’s copy the below PHP code examples to call the function. We can pass our input URL string via the $request
variable (enclosed in quotations):
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\DomainApi(
new GuzzleHttp\Client(),
$config
);
$request = new \Swagger\Client\Model\ValidateUrlRequestSyntaxOnly(); // \Swagger\Client\Model\ValidateUrlRequestSyntaxOnly | Input URL information
try {
$result = $apiInstance->domainGetTopLevelDomainFromUrl($request);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DomainApi->domainGetTopLevelDomainFromUrl: ', $e->getMessage(), PHP_EOL;
}
?>
That’s all the code we’ll need! Now we can easily get the top-level domain from any input URL. Our API response will also confirm if the input URL was valid to begin with.