Integrate the Traffic Sources API in PHP
You need to surface where your traffic comes from and act on it: block ad placements from certain sources, enrich signups with country traffic share, or audit partners by their referral mix. By the end of this guide, you’ll call Klazify’s Traffic Sources endpoint from PHP, parse ranks and traffic-share fields, and wire the results into a pipeline that caches, retries, and maps data into your internal model.
Why Klazify is a great fit for traffic intelligence in PHP-based pipelines
When you’re building a PHP integration to understand how domains acquire traffic (search, social, referrals, etc.), you need more than raw hits—you need context. Klazify’s domain intelligence API provides both traffic source signals and rich categorization so you can enforce brand safety, optimize campaigns, and enrich customer data with reliable domain insights.
- Accurate categorization with AI: The same models that classify domains and URLs also ground your traffic analysis in IAB-aligned categories. If you’re reviewing where an ad ran, you can validate both its category and its traffic profile.
- Global coverage: Traffic and category analysis works across languages and geographies, supporting international sites and localized campaigns.
- Real-time classification: You’re not bound to stale lists. Fresh crawls and analysis enable up-to-date category and traffic insights.
- Industry-level categories: IAB taxonomy is available so downstream ad tech systems and brand safety rules can be applied consistently.
- Simple integration: A clean REST interface means you can POST a URL and get back traffic ranks, monthly visits, engagement, sources, and countries—ready to plug into PHP services.
- Compliance and filtering: Combine traffic sources with categories to whitelist or exclude domains with confidence (for example, block a campaign on a domain if a large share is driven by a channel you don’t trust).
You can start integrating with a free trial in the Starter plan ($39.99/mo after a 7-day trial). Failed or unreachable calls are not billed. Explore more at klazify.com and the linked resources below.
What you’ll build: call the Traffic Sources endpoint and act on it
The core step is a POST to the Traffic Sources endpoint with a URL. You’ll receive traffic ranks and distribution by channel and country, which you can use to:
- Block ad delivery on domains whose traffic_sources skew too much to low-quality referrals.
- Enrich user or account records with top_countries to improve geo routing or personalization.
- Audit partners by comparing global_rank, country_rank, and monthly_visits against your thresholds.
Traffic Sources API: endpoint and curl example
Use Bearer authentication and send the URL in JSON. Here’s a copy-pasteable request you can run from any environment (the example domain is included only in the curl to demonstrate the payload format):
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"}'
In your integration, replace YOUR_API_KEY with your token and the url with the target domain or URL from your queue or ingestion pipeline. The response includes fields such as global_rank, country_rank, category_rank, monthly_visits, engagement, traffic_sources, and top_countries.
PHP integration: making the request and parsing key fields
Below is a minimal PHP example using cURL to POST and parse the response. It reads the fields your workflow typically needs and shows safe defaults when something isn’t present.
<?php
$apiKey = "YOUR_API_KEY";
$endpoint = "https://www.klazify.com/api/domain_traffic_intelligence";
$payload = json_encode(["url" => "https://example.com"]);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . $apiKey,
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
// Not billed for failed or unreachable calls
error_log("Traffic API error: " . $err);
exit;
}
if ($httpCode < 200 || $httpCode >= 300) {
error_log("Traffic API HTTP " . $httpCode . " response: " . $response);
exit;
}
$data = json_decode($response, true);
// Defensive extraction
$globalRank = $data["global_rank"] ?? null;
$countryRank = $data["country_rank"] ?? null;
$categoryRank = $data["category_rank"] ?? null;
$monthlyVisits = $data["monthly_visits"] ?? null;
$engagement = $data["engagement"] ?? [];
$trafficSources = $data["traffic_sources"] ?? [];
$topCountries = $data["top_countries"] ?? [];
// Example: basic guardrail
if ($trafficSources) {
$referralShare = $trafficSources["referrals"] ?? 0.0;
if ($referralShare > 0.65) {
// Flag for review
error_log("High referral share; consider excluding from certain campaigns.");
}
}
// Cache by registrable domain (e.g., example.com) with TTL of your choice
// Store $data in Redis/memcached/DB keyed by the domain
echo "Global Rank: " . ($globalRank ?? "n/a") . PHP_EOL;
echo "Monthly Visits: " . (is_null($monthlyVisits) ? "n/a" : $monthlyVisits) . PHP_EOL;
echo "Top Country: " . (!empty($topCountries) ? $topCountries[0]["country"] ?? "n/a" : "n/a") . PHP_EOL;
?>
Optional JavaScript example for data engineers
If you validate results or run enrichment flows in Node.js, here’s a snippet that fetches the same endpoint and highlights where to read traffic distribution and engagement fields.
import fetch from "node-fetch";
async function getTraffic(url) {
const res = await fetch("https://www.klazify.com/api/domain_traffic_intelligence", {
method: "POST",
headers: {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify({ url })
});
if (!res.ok) {
const body = await res.text();
throw new Error(`HTTP ${res.status}: ${body}`);
}
const data = await res.json();
// Pull out the fields you care about
const {
global_rank,
country_rank,
category_rank,
monthly_visits,
engagement,
traffic_sources,
top_countries
} = data;
// Example rule: block if bounce rate is too high
const bounce = engagement?.bounce_rate;
if (typeof bounce === "number" && bounce > 0.8) {
console.warn("Bounce rate too high; exclude from premium inventory.");
}
return {
global_rank,
country_rank,
category_rank,
monthly_visits,
engagement,
traffic_sources,
top_countries
};
}
getTraffic("https://example.com")
.then(console.log)
.catch(console.error);
How to interpret the returned fields in workflows
The Traffic Sources endpoint returns several fields that plug directly into decision logic:
- global_rank: Use for overall site prominence checks in audits and partner due diligence.
- country_rank: Gate spend by country-specific rank for region-focused campaigns.
- category_rank: Combine with content categorization to evaluate niche-specific authority.
- monthly_visits: Size traffic at a glance and threshold small, new, or low-visibility sites.
- engagement: Pull metrics like time-on-site or bounce rate for quality heuristics.
- traffic_sources: Channel distribution. Apply channel allow/deny policies and detect anomalies (e.g., unusually high referrals).
- top_countries: Weight geo allocations, personalize content, or route moderation queues to the right locales.
Add categorization to your traffic intelligence
Many teams pair traffic sources with categorization for enforcement and reporting. Below is the official Klazify response example for categorization and company context. You can call categorization via the main endpoint to enrich the same domain you analyze for traffic. Use the categories array, IAB mappings, company objects, and similar_domains to deepen your scoring logic and downstream tags.
{
"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 with traffic intelligence:
- domain.categories: Map to IAB for brand safety or to segment traffic-source thresholds per category.
- domain.logo_url: Display a logo alongside traffic metrics in internal dashboards.
- objects.company.*: Enrich CRM or lead scoring with size, revenue, location, and tags. Combine with monthly_visits to refine account tiering.
- domain_registration_data: Weigh domain age and expiration risk in trust scoring for new partners.
- similar_domains: Expand analysis to adjacencies; if one domain is risky, queue neighbors for review.
Using traffic sources programmatically: field-to-use-case mapping
| Field | What it tells you | Action | Example policy |
|---|---|---|---|
| global_rank | Overall prominence | Gate ad spend or priority | Only allow top N ranks for brand campaigns |
| country_rank | Prominence per country | Local market targeting | Exclude sites with weak rank in target geo |
| category_rank | Authority within category | Contextual ad placements | Require strong rank in niche categories |
| monthly_visits | Traffic scale | Partner qualification | Set minimum visit thresholds |
| engagement | Quality signals | Quality scoring | Exclude high bounce rate sites from premium |
| traffic_sources | Channel mix | Channel-specific rules | Cap spend when referrals share spikes |
| top_countries | Geo distribution | Geo routing & content | Adjust creatives by country share |
Operational guidance: throughput, caching, errors, and unknown domains
Batching and rate limits
Invoke the Traffic Sources endpoint in batches aligned with your processing window. If your pipeline processes thousands of domains, parallelize with a worker pool and backoff. Observe your plan’s rate allowances in the Documentation and adapt concurrency accordingly.
Caching per registrable domain
Cache responses keyed by the registrable domain (e.g., example.com). Choose TTLs based on how often you expect traffic patterns to change. A 24–72 hour TTL is common, but tune this to your refresh cadence. Store the entire JSON blob so later consumers can read new fields without refetching.
Handling errors and non-billable failures
Network timeouts, DNS failures, or unreachable hosts can occur. Since failed or unreachable calls are not billed, you can safely implement retries with exponential backoff and a bounded retry budget. Log HTTP status and response bodies to a dead-letter queue for inspection.
Unknown or new domains
For newly registered or low-traffic domains, certain fields might be missing or null. Apply sensible defaults (e.g., treat missing ranks as low authority) and schedule a delayed recheck. If category data is essential, call categorization and use the IAB mapping to infer how to handle the traffic profile.
Mapping to your internal taxonomy
If your system uses custom categories, map Klazify’s IAB-based names or codes to your internal labels once, then reuse that mapping table to classify traffic governance rules. For example, maintain a policy table like: if category in {“/News & Media/*”} and referral share > X, then restrict placement type.
Pipeline patterns: putting it all together
Most teams adopt a multi-stage flow that looks like this:
- Normalize the input URL to its registrable domain. Strip tracking params and fragments.
- Check cache. If stale or missing, POST to the Traffic Sources endpoint.
- Optionally call categorization for IAB categories and company data to complement traffic signals.
- Score: combine ranks, monthly_visits, engagement, traffic_sources, and category to produce a quality score.
- Apply actions: block, throttle, or qualify partners; enrich CRM records; route moderation; geo personalization.
- Persist raw response plus derived features for audit and model training.
When expanding coverage, consult MCP for account management and plan controls, and ensure your workers respect your allowed throughput.
Quality checks you can implement on day one
- Null and shape checks: Ensure fields like traffic_sources exist before arithmetic. Default missing shares to 0.0.
- Thresholds with hysteresis: Avoid flapping on minor rank or share changes by using enter/exit thresholds.
- Country weighting: If top_countries shows a mismatch with your buyer geo, shift budget or creative.
- Time-based revalidation: Recheck domains on a schedule, even if cached, to capture trend shifts.
- Explainability: Store per-field contributions (e.g., how referral share affected the final score) for quick audits.
Plan, pricing, and getting started
You can start with the Starter plan at $39.99/mo, which includes a 7-day trial. This lets you prototype the traffic intelligence workflow, test caching and mapping, and validate decision quality before scaling. Create an account here: Register. For full endpoint details and any updates, see the Documentation. You can also explore more capabilities across the platform at klazify.com.
FAQ
-
Can I send either a domain or a full URL?
Yes. Send the value in the JSON body under "url". Normalize to the registrable domain in your own code for caching consistency. -
How should I handle rate limits?
Use a small worker pool with exponential backoff and respect your plan’s throughput. Batch requests over time and cache aggressively to minimize re-fetches. -
What happens if the site is down or unreachable?
Implement retries. Failed or unreachable calls are not billed, and you should log and reschedule those domains. -
How do I reconcile Klazify categories with our internal labels?
Create a mapping table from Klazify’s IAB-linked categories to your taxonomy. Apply it at ingestion so downstream systems see consistent labels. -
Can I store and re-use the API responses?
Yes. Cache the full JSON for each domain with a TTL aligned to your refresh policy so you can reuse fields like ranks, traffic_sources, and top_countries without repeated calls.
Ready to enrich domains with traffic sources, engagement, and categories? Create your account and start integrating in minutes: Register.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free