How to Get a Company's City and Country in PHP
You have a signup form or inbound lead list filled with domains, and your team needs each company’s city and country to route accounts, comply with data residency, or prioritize sales outreach. In this guide you’ll plug Klazify’s domain_company endpoint into your PHP stack, extract city and country (plus a few business signals), and make the results production-ready with caching, batching, and fallbacks.
Why Klazify is ideal for extracting company location from a domain
When your goal is to get the city and country for any company website, classification quality and data freshness directly affect routing and enrichment. Klazify analyzes full website content and signals to retrieve company information—crucial when a homepage or “About” page is sparse or localized. Here’s how it fits the specific job of turning a domain into dependable location data:
- Accurate website categorization using AI: Location and business context are derived from on-site content, not just WHOIS or metadata. This helps detect the right entity even when multiple brands share a parent domain.
- Global coverage: Many sites publish in local languages. Klazify’s analysis works across languages so you can extract city and country for regional brands, subsidiaries, and non-English websites.
- Real-time classification: Fresh crawls matter when companies move HQs or open new offices. You can rely on current content rather than static lists.
- Industry-level categories (IAB): Beyond city and country, Klazify maps sites to IAB categories so you can also segment by industry and align routing with territory and vertical.
- Simple API integration: A single REST POST to retrieve company fields (city, stateCode, countryCode) lets you enrich any domain in your PHP backend or ETL job.
- Compliance and filtering: Combine precise categories with country data to enforce geographic policies (e.g., block signups in certain regions or trigger additional verification).
If you’re building geo-routing for sales, filtering signups by region, or enriching leads for analytics, Klazify gives you the location fields you need and the categories to act on them immediately.
What we’ll build: domain to city and country in PHP
We’ll call the domain_company endpoint with a website URL and parse the fields your pipeline expects:
- name
- city
- stateCode
- countryCode
- employeesRange
- revenue (returned as a range by this endpoint)
- raised
- tags
We’ll also cover how to cache per domain, queue batches, and handle unknown or newly launched domains. If you don’t yet have an API key, create one in minutes here: Register. You can also review the full API reference: Documentation.
The endpoint you’ll use
We’ll use the following endpoint to retrieve company details directly from a domain or URL:
- POST https://www.klazify.com/api/domain_company
Authentication uses a Bearer token. The JSON body includes a single field, url. Failed or unreachable calls are not billed. You can start on the Starter plan ($39.99/mo) with a 7-day trial.
cURL request you can copy
Send a POST with the url you want to enrich. This example uses a real news domain purely for demonstration in the request (do not hardcode this domain in your application):
curl -X POST "https://www.klazify.com/api/domain_company" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://cbsnews.com"}'
On success, you’ll receive a JSON document with a company object. The fields you’ll likely use first are city, stateCode, and countryCode for geographic routing and reporting. You can also use tags, employeesRange, revenue (as a range), and raised to improve lead scoring and segmentation.
PHP: extract city and country from the response
This PHP snippet posts a domain, validates the response, and reads the city and countryCode fields. Replace YOUR_API_KEY with your Klazify API key.
<?php
$apiUrl = "https://www.klazify.com/api/domain_company";
$payload = json_encode(["url" => "https://cbsnews.com"]);
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer YOUR_API_KEY",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
// Network or TLS error. You are not billed for unreachable calls.
error_log("Request error: " . $err);
exit;
}
if ($httpCode < 200 || $httpCode >= 300) {
// Handle non-2xx. Consider retry with backoff for transient 5xx.
error_log("HTTP $httpCode response: " . $response);
exit;
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("Invalid JSON: " . json_last_error_msg());
exit;
}
// Safely navigate to company fields (only rely on documented fields).
$company = $data["objects"]["company"] ?? null;
if (!$company) {
// New or unknown domain? Queue a re-check, fallback, or manual review.
error_log("No company object found in response");
exit;
}
$name = $company["name"] ?? null;
$city = $company["city"] ?? null;
$stateCode = $company["stateCode"] ?? null;
$countryCode = $company["countryCode"] ?? null;
$employees = $company["employeesRange"] ?? null;
$revenueRange = $company["revenue"] ?? null; // Range for this endpoint
$raised = $company["raised"] ?? null;
$tags = $company["tags"] ?? [];
// Use city and countryCode in your routing logic.
printf("Company: %s\nCity: %s\nState: %s\nCountry: %s\n",
$name, $city, $stateCode, $countryCode);
// Example: derive region for assignment
switch ($countryCode) {
case "US":
case "CA":
$region = "NA";
break;
case "GB":
case "DE":
case "FR":
$region = "EU";
break;
default:
$region = "ROW";
}
printf("Assigned region: %s\n", $region);
// Cache by domain to avoid repeat lookups.
?>
A JavaScript example (optional for ETL or Node backends)
If your enrichment job runs in Node.js, here’s a minimal example that reads the same fields:
import fetch from "node-fetch";
async function enrich(url) {
const res = await fetch("https://www.klazify.com/api/domain_company", {
method: "POST",
headers: {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify({ url })
});
if (!res.ok) {
// Handle non-2xx (e.g., 429, 5xx). Retry with backoff when appropriate.
throw new Error(`HTTP ${res.status}`);
}
const data = await res.json();
const company = data?.objects?.company;
if (!company) return null;
const { name, city, stateCode, countryCode, employeesRange, revenue, raised, tags } = company;
return { name, city, stateCode, countryCode, employeesRange, revenue, raised, tags };
}
enrich("https://cbsnews.com")
.then(info => console.log(info))
.catch(err => console.error(err));
Understanding the JSON fields you’ll use
Your PHP pipeline typically needs the following fields from objects.company:
| Field | Purpose | How to use |
|---|---|---|
| name | Company display name | Show in CRM or enrichment logs for operator visibility |
| city | Primary city | Territory routing, SLA calculation, localization |
| stateCode | Regional code (e.g., US state) | US coverage routing or tax logic |
| countryCode | ISO country code | Data residency, geo eligibility, currency model selection |
| employeesRange | Workforce size (range) | Lead scoring and stratified routing (SMB vs Enterprise) |
| revenue | Revenue (range) | Prioritize high-revenue prospects; display as a bucket |
| raised | Funding (range or amount) | Segment startups vs bootstrapped companies |
| tags | Business tags | Search and reporting filters; downstream ML features |
Official example response: how categories and company data appear
Below is the official example response format you’ll see from Klazify. This sample shows how categories, social media, logo_url, company, domain registration data, and similar domains are structured. Use it to understand where company fields like city and countryCode live when present in the response. Do not modify this sample; it’s provided for reference only.
{
"domain": {
"categories": [
{
"confidence": 0.92,
"name": "/Computers & Electronics/Consumer Electronics",
"IAB-632-596": "Consumer Electronics/Technology & Computing/Consumer Electronics"
},
{
"confidence": 0.89,
"name": "/Internet & Telecom/Mobile & Wireless/Mobile Phones"
}
],
"social_media": null,
"logo_url": "https://klazify.s3.amazonaws.com/2110787991611585019600ed5fb1d1300.04730104.png"
},
"success": true,
"objects": {
"company": {
"url": "https://www.apple.com/",
"name": "Apple",
"city": "Cupertino",
"stateCode": "CA",
"countryCode": "US",
"employeesRange": "100K+",
"revenue": 274515000000,
"raised": null,
"tags": [
"E-commerce",
"Consumer Electronics",
"Mobile",
"B2C"
],
"tech": [
"omniture_adobe_analytics",
"atlassian_confluence",
"successfactors",
"apache_apex",
"talend",
"oracle_peoplesoft",
"salesforce",
"stripe",
"dell_boomi_atomsphere",
"gigya",
"sage_50cloud",
"quickbooks",
"webmethods",
"apache_tomcat",
"alteryx",
"tibco_rendezvous",
"atlassian_jira",
"..."
]
}
},
"domain_registration_data": {
"domain_age_date": "1987-02-19",
"domain_age_days_ago": "13026",
"domain_expiration_date": "2030-02-20",
"domain_expiration_days_left": "123"
},
"similar_domains": [
"bestbuy.com",
"icloud.com",
"microsoft.com",
"macrumors.com",
"google.com",
"samsung.com",
"twitter.com",
"hp.com",
"bhphotovideo.com",
"dell.com"
]
}
Key parts you’ll consume:
- objects.company.city and objects.company.countryCode: Primary fields for regional routing, compliance, and language settings.
- objects.company.stateCode: Useful for in-country routing (e.g., US states).
- objects.company.tags and employeesRange: Use as signals for lead scoring and prioritization.
- domain.categories with IAB mapping: If you also need brand safety or industry targeting, map these to your own taxonomy or feature store.
How to act on city and country in your systems
Once you have city and countryCode for a domain, here are concrete ways to use them:
- Auto-assign accounts to regional sales teams and SLAs.
- Gate features for restricted countries or trigger added verification for high-risk regions.
- Localize currency, format, and compliance flows based on countryCode.
- Aggregate reports by country/region to understand geographic traction.
Operational details: batching, caching, and unknown domains
Batching strategy
- Queue domains and process them in controlled batches (e.g., in a worker or cron) to respect rate limits. If you hit throttling, back off and retry.
- De-duplicate within a batch and across retries to avoid unnecessary calls.
Caching per domain
- Cache results keyed by normalized domain (lowercase, strip protocol, strip www) for a TTL (e.g., days to weeks). Location data changes infrequently, so caching dramatically reduces calls and latency.
- Invalidate cache when you detect a significant site update, or on a schedule if you require fresher data.
Handling unknown or new domains
- If the API can’t return a company object (e.g., brand new site), store a “pending enrichment” status and retry later.
- Fallback: If you have the user’s self-declared country, use it temporarily but prefer the API result once available.
- Log misses for manual review if the domain is strategically important.
Resilience and billing
- Failed or unreachable calls are not billed. Implement retries with exponential backoff for transient errors.
- Separate network errors from non-2xx HTTP responses to tune your retry policy.
Mapping categories to your taxonomy
If you also need to align industry categories with your internal taxonomy, use the categories provided in the categorization response (IAB mapping). Maintain a lookup table that translates Klazify’s categories to your internal labels. For example:
- Directly store the string under domain.categories[].name and its IAB code when present.
- When a category is unfamiliar, log and review it, then extend your mapping table.
This enables consistent analytics and brand-safety rules across systems while you still use city and countryCode for geo policies.
Security, privacy, and compliance notes
- Store only the fields you need. For geo rules, city and countryCode may be sufficient.
- Keep your API key in environment variables or a secrets manager.
- Log minimal PII and scrub payloads in app logs where not necessary.
Putting it all together in your pipeline
Here’s a typical flow for PHP backends and ETL jobs:
- Normalize domain input (e.g., lowercase, remove scheme and path; or submit a full URL as required).
- Check cache. If hit, use cached city and countryCode immediately.
- If miss, POST to https://www.klazify.com/api/domain_company with Bearer auth and JSON payload {"url":"https://domain.com"}.
- Parse objects.company.city, stateCode, and countryCode; store alongside your account or lead record.
- Apply routing and compliance logic based on countryCode and, if applicable, stateCode.
- Backfill employeesRange, revenue (range), raised, and tags for lead scoring and segmentation.
- Cache the result with a sensible TTL. On errors, retry with backoff and mark for later processing if needed.
Where to go next
For a broader domain intelligence workflow (logos, social links, IAB categories, tech detection, registration data), explore the API reference and model catalog:
FAQ
- Which fields should I persist for geo-routing? Persist city, stateCode (if applicable), and countryCode. Keep a timestamp so you can refresh periodically.
- What if a domain returns no company object? Queue a retry, store a “pending enrichment” flag, and optionally request user confirmation of location in the interim. You are not billed for unreachable calls.
- How do I handle rate limits? Batch requests, add backoff and jitter on retry, and cache results per domain to reduce call volume. For plan-specific limits, see the API documentation.
- Is revenue an exact figure? For the domain_company endpoint, treat revenue as a range and display it as a bucket in your UI or scoring model.
- Can I also use categories for brand safety or analytics? Yes. Use the categories and IAB mappings in the categorization response to align with your internal taxonomy and apply brand-safety rules.
Spin up your key and ship this integration in minutes. Create a free account now: Register. Then follow the Documentation to extend beyond city and country with categories, tags, and more.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free