How to Get a Website's Traffic Sources in PHP
Your team needs to pull reliable traffic source breakdowns for any domain, then route that data into a PHP backend to enrich signups, vet publishers, or audit where ads run. By the end of this guide, you’ll call Klazify’s traffic intelligence endpoint, parse traffic sources in PHP or JavaScript, cache results per domain, and wire the fields into your pipeline for ranking, filtering, and reporting.
Why Klazify is a strong fit for traffic-source intelligence you can use in PHP
Traffic sources only make sense when you can trust the classification and context around the domain. Klazify analyzes page content and domain signals to deliver traffic insights that plug into your brand safety, enrichment, and analytics workflows.
- Accurate website categorization using AI: Traffic data is more useful when the site is correctly classified. Klazify models analyze full-site content, not just metadata, so your traffic-source dashboards can filter or group by the right IAB categories.
- Global coverage: Multilingual analysis helps you compare traffic profiles for international domains. This is critical when you’re evaluating markets or running publisher audits across multiple locales.
- Real-time classification: Domains change; Klazify’s classification keeps pace, so your traffic-source ratios align with current content rather than stale category lists.
- Industry-level categories: With IAB taxonomy mapping, you can segment traffic sources (for example, high-direct vs. high-search sites) by standardized industry categories without custom heuristics.
- Simple API integration: A single REST call returns fields like global_rank, country_rank, category_rank, monthly_visits, engagement, traffic_sources, and top_countries that you can push straight into your PHP services or data pipelines.
- Compliance and filtering: Pair traffic sources with precise categorization to enforce where ads can run or which referrals are allowed in your app, improving your brand safety posture.
If you’re new to Klazify, you can explore the product at klazify.com and create a free account to start testing the API.
What you’ll build: get traffic sources, ranks, and visits from one endpoint
We’ll call a single endpoint to retrieve:
- global_rank, country_rank, category_rank: High-level rank signals you can sort or filter by.
- monthly_visits: Estimated visit volumes you can use to prioritize opportunities.
- engagement: Visit-duration and page-depth type signals for quality scoring.
- traffic_sources: Ratio of direct, search, social, referrals, mail, and ads traffic to understand acquisition mix.
- top_countries: Geo breakdown useful for market focus, geo-compliance, and sales routing.
We’ll trigger the request from PHP or JavaScript, then show how to store and reuse the results efficiently in production.
Endpoint and authentication
Use a POST request with a Bearer token to pass the target URL/domain:
- Endpoint: https://www.klazify.com/api/domain_traffic_intelligence
- Auth: Authorization: Bearer YOUR_API_KEY
- Body: JSON with the target URL, for example {"url":"https://cbsnews.com"}
Notes:
- Send a single domain/URL per request. For scale, batch requests in your job queue and cache results by domain.
- Failed or unreachable calls are not billed.
- You can review request/response structure and additional endpoints in the Documentation.
cURL: fetch traffic sources and engagement
curl -X POST "https://www.klazify.com/api/domain_traffic_intelligence" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://cbsnews.com"}'
Replace YOUR_API_KEY with your token. The response includes fields such as global_rank, country_rank, category_rank, monthly_visits, engagement, traffic_sources, and top_countries that you can map into your data model.
Code: parse traffic sources in JavaScript and PHP
JavaScript (Node.js) example
import fetch from "node-fetch";
const API_URL = "https://www.klazify.com/api/domain_traffic_intelligence";
const API_KEY = process.env.KLAZIFY_API_KEY; // store securely
async function getTrafficIntel(targetUrl) {
const res = await fetch(API_URL, {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ url: targetUrl })
});
if (!res.ok) {
// Not billed for failed/unreachable calls, but still log
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
const data = await res.json();
// Safely read traffic intelligence fields
const {
global_rank,
country_rank,
category_rank,
monthly_visits,
engagement,
traffic_sources,
top_countries
} = data || {};
// Example: Normalize for storage
return {
domain: targetUrl,
ranks: {
global: global_rank ?? null,
country: country_rank ?? null,
category: category_rank ?? null
},
monthly_visits: monthly_visits ?? null,
engagement: engagement ?? null, // keep shape as returned for BI
sources: traffic_sources ?? null, // direct/search/social/referrals/mail/ads
top_countries: top_countries ?? [] // array with country share
};
}
(async () => {
try {
const intel = await getTrafficIntel("https://cbsnews.com");
console.log(JSON.stringify(intel, null, 2));
// Next: upsert intel into your DB and cache by domain
} catch (err) {
console.error(err);
}
})();
PHP example
<?php
$apiUrl = "https://www.klazify.com/api/domain_traffic_intelligence";
$apiKey = getenv("KLAZIFY_API_KEY");
$target = "https://cbsnews.com";
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . $apiKey,
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["url" => $target]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
// Not billed for failed/unreachable calls, but still handle errors
throw new Exception("HTTP $httpCode: " . $response);
}
$data = json_decode($response, true);
// Safely read fields; they may be null for unknown/new domains
$globalRank = $data["global_rank"] ?? null;
$countryRank = $data["country_rank"] ?? null;
$categoryRank = $data["category_rank"] ?? null;
$monthlyVisits = $data["monthly_visits"] ?? null;
$engagement = $data["engagement"] ?? null;
$sources = $data["traffic_sources"]?? null;
$topCountries = $data["top_countries"] ?? [];
// Example: build a normalized row for storage
$result = [
"domain" => $target,
"ranks" => [
"global" => $globalRank,
"country" => $countryRank,
"category" => $categoryRank
],
"monthly_visits" => $monthlyVisits,
"engagement" => $engagement,
"traffic_sources" => $sources,
"top_countries" => $topCountries
];
echo json_encode($result, JSON_PRETTY_PRINT);
How to use the returned fields in your pipeline
- Ranking and allow/block logic: Use global_rank, country_rank, and category_rank thresholds to gate domains for ad placements or partnerships.
- Market and geo routing: Use top_countries to decide which regional sales queue or compliance ruleset to apply.
- Quality scoring: Combine monthly_visits and engagement to prioritise domains with meaningful audiences and lower bounce tendencies.
- Acquisition mix analysis: Use traffic_sources to categorize sites by dominant acquisition (direct, search, social, referrals, mail, ads) and tailor campaign strategies.
- Caching: Cache by eTLD+1 (e.g., example.com). Invalidate or refresh on a cadence appropriate to your reporting (e.g., daily or weekly refresh windows).
Combine traffic sources with categorization and company data
For many workflows (brand safety, enrichment, and targeting), you’ll want traffic intelligence alongside categories, IAB mappings, logos, and company metadata. Here’s the official response example format you can expect from Klazify’s categorization endpoint. This sample shows the structure for categories, logo_url, and company details, which you can store together with traffic intelligence for a single source of truth per domain.
{
"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"
]
}
How to use these fields:
- domain.categories: Use name for broad-to-specific grouping and IAB-632-596 for IAB taxonomy mapping. Aligns traffic-source analysis to industry-standard categories.
- domain.logo_url: Brand visuals in dashboards, CRM, or publisher overview pages.
- objects.company: Enrich leads or publisher records with name, geo, size (employeesRange), revenue, and tags; cross-reference with traffic_sources for scoring.
- domain_registration_data: Add domain age and expiration signals to your risk or prioritization models.
- similar_domains: Expand prospecting lists and run the same traffic intelligence lookup on related sites.
Mapping traffic sources and categories to your own taxonomy
Most teams have their own source taxonomy and category model. To bridge:
- Traffic sources: Map traffic_sources keys (such as direct, search, social, referrals, mail, ads) to your internal acquisition enums. Keep unmapped fields in a catch-all to avoid data loss.
- IAB mapping: domain.categories includes IAB taxonomy references (e.g., IAB-632-596). Store both the free-form category name and the IAB code for reversible mapping.
- Segmentation: Use category_rank and global_rank bins to form tiers (e.g., T1–T4) for reporting or auto-approval logic.
Operational guidance: scale, batching, caching, and unknown domains
- Batching and queues: For large lists, push domains into a queue and fan out workers that POST to the endpoint. Respect concurrency in your job runners to keep latency predictable.
- Caching policy: Cache by eTLD+1 and set a refresh interval that aligns with your reporting cadence (e.g., daily or weekly). Store the raw JSON alongside normalized columns so you can reprocess without hitting the API again.
- Unknown or new domains: Some fields may be null or absent if a domain is very new or unreachable. Code defensively (null checks) and schedule a retry delay rather than looping immediately.
- Rate limits and retries: Handle HTTP errors gracefully with exponential backoff. Keep lightweight metrics (success/failure counts, p95 latency) to tune concurrency.
- Data lineage: Persist response timestamps for reproducibility in analytics. If you denormalize, also keep the original JSON blob.
- Cost controls: Failed or unreachable calls are not billed. Cache aggressively to reduce duplicate lookups. Start on an entry plan and scale as you integrate more workflows.
Pricing, signup, and where to go next
You can start testing with a 7-day trial. The Starter plan is $39.99/mo. Create your account and get an API key here: Register. Explore more capabilities in the Documentation, and learn about management and controls in MCP. You can also visit the homepage at klazify.com to see everything you can build with the API.
Field-to-action quick reference
| Field | What it tells you | Common actions |
|---|---|---|
| global_rank | Overall popularity/reach indicator | Sort candidates, set minimum quality thresholds |
| country_rank | Popularity in a specific country | Geo routing, regional targeting, compliance checks |
| category_rank | Standing within its content category | Tiering for ad approvals, competitive benchmarking |
| monthly_visits | Estimated traffic volume | Opportunity sizing, prioritization |
| engagement | Quality of visits (e.g., duration, depth) | Lead scoring, risk heuristics, publisher evaluation |
| traffic_sources | Acquisition split (direct/search/social/referrals/mail/ads) | Campaign planning, brand safety controls, audience mix analysis |
| top_countries | Geographic distribution of visits | Market focus, localization, regulatory gating |
| domain.categories + IAB | Standardized content category mapping | Ad targeting, filtering, taxonomy alignment |
FAQ
-
Can I request traffic data for multiple domains at once?
Send one domain per request and parallelize via your own job queue. Cache responses by domain to avoid duplicate lookups. -
How should I handle missing or null fields?
Treat missing fields as unknown and retry on a schedule. Don’t block pipelines on optional data; store nulls and update when available. -
How often should I refresh traffic sources?
Match your reporting cadence. Many teams refresh weekly or monthly. Keep a timestamp on each stored response so you can track freshness. -
What happens if the domain is unreachable?
You won’t be billed for failed or unreachable calls. Log the event and retry later with backoff. -
Can I align categories with my internal taxonomy?
Yes. Use the returned IAB mapping to bridge to your internal categories. Store both the free-form category name and the IAB code for flexibility.
Ready to enrich your PHP stack with trustworthy traffic sources and domain intelligence? Create your free account to get an API key and start integrating today: Register.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free