Integrate the Contextual Targeting API in PHP

December 01, 2026
Integrate the Contextual Targeting API in PHP

You need to decide whether an ad can run next to a website’s content, but a domain name alone does not tell you what the site covers. With Klazify’s categorization endpoint, you can submit a URL from PHP, inspect its categories and confidence values, and route the result into an allow, block, or review decision.

Why use domain classification for contextual targeting?

Contextual targeting starts with the content associated with an ad placement, rather than assuming that every page or domain is suitable for every campaign. A category such as /News can be useful when a campaign wants to include news sites, exclude them, or audit how often ads appear alongside that content.

Illustration: Integrate the Contextual Targeting API in PHP

Documentation describes a REST integration that returns categorization alongside other domain information. Klazify analyzes website content rather than relying only on domain names or metadata, supports multilingual analysis, and maps content to a hierarchical taxonomy that includes IAB categories. Its categorization system contains 621 categories.

That combination is useful for an ad decision pipeline: the classification gives you a content signal, while the IAB mapping can help translate it into a common advertising vocabulary. Company, logo, social, and technology data can add context to an audit, but they should not replace the category decision itself.

A category is not a guarantee that a placement is safe or compliant. Treat the response as an input to your own campaign rules, and reserve a review path for missing, ambiguous, or unexpected results. Evaluate classifications against a representative set of placements before enforcing a policy at scale.

Send a categorization request

Replace YOUR_API_KEY with your Klazify API key and run this request. The endpoint accepts a JSON object containing the URL to classify and uses a Bearer token for authentication.

curl -X POST 'https://www.klazify.com/api/categorize' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://cbsnews.com"}'

For this example domain, the documented categorization includes /News with a confidence of 0.97. A targeting service could match that category against a campaign’s policy and record the category and confidence for later auditing.

The endpoint also returns other domain signals, including company, logo, social, and technology information where available. Do not assume every signal will be populated for every domain. The response example below illustrates the structure with a different company and should not be read as the response to the request above.

Call the endpoint from PHP

The following script accepts the URL to classify as its first command-line argument and reads the API key from an environment variable. It prints each returned category and its confidence so that your application can pass those values to its own targeting rules.

<?php

$apiKey = getenv('KLAZIFY_API_KEY');
$url = $argv[1] ?? '';

if (!$apiKey || !$url) {
    fwrite(STDERR, "Set KLAZIFY_API_KEY and pass a URL as an argument.\n");
    exit(1);
}

$payload = json_encode(['url' => $url]);
if ($payload === false) {
    fwrite(STDERR, "Could not encode request.\n");
    exit(1);
}

$curl = curl_init('https://www.klazify.com/api/categorize');
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => $payload,
]);

$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($body === false) {
    fwrite(STDERR, "Request failed: " . curl_error($curl) . "\n");
    curl_close($curl);
    exit(1);
}
curl_close($curl);

if ($status < 200 || $status >= 300) {
    fwrite(STDERR, "HTTP request failed with status " . $status . "\n");
    exit(1);
}

$data = json_decode($body, true);
if (!is_array($data) || ($data['success'] ?? false) !== true) {
    fwrite(STDERR, "Classification unavailable or response invalid.\n");
    exit(1);
}

$categories = $data['domain']['categories'] ?? [];
if (!is_array($categories) || count($categories) === 0) {
    echo "No categories returned; send for review.\n";
    exit(0);
}

foreach ($categories as $category) {
    $name = $category['name'] ?? '';
    if ($name === '') {
        continue;
    }
    $confidence = $category['confidence'] ?? 'unknown';
    echo $name . " | confidence: " . $confidence . "\n";
}

Run the script with PHP’s cURL extension enabled, supplying the target URL as the argument. Keep the key in your deployment’s secret store or environment rather than committing it to source control. In a web application, apply the same validation and error handling inside your service layer rather than accepting an unrestricted command-line value.

The script reports categories instead of making a final ad decision. That separation is intentional: one campaign may target /News, while another may require a review before buying inventory in that category. Store the returned category and confidence alongside the resulting policy decision so an auditor can see why it was made.

Python alternative for a data pipeline

If a data engineering job handles enrichment before your PHP application consumes it, this Python example makes the same call using the standard library. It accepts the URL as its first argument and uses the same environment variable for the key.

import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

api_key = os.environ.get("KLAZIFY_API_KEY")
if not api_key or len(sys.argv) < 2:
    sys.exit("Set KLAZIFY_API_KEY and pass a URL as an argument.")

payload = json.dumps({"url": sys.argv[1]}).encode("utf-8")
request = Request(
    "https://www.klazify.com/api/categorize",
    data=payload,
    headers={
        "Authorization": "Bearer " + api_key,
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urlopen(request) as response:
        data = json.load(response)
except HTTPError as exc:
    sys.exit("HTTP request failed: " + str(exc.code))
except (URLError, OSError, ValueError) as exc:
    sys.exit("Classification unavailable or response invalid: " + str(exc))

if not isinstance(data, dict) or data.get("success") is not True:
    sys.exit("Classification unavailable or response invalid.")

domain = data.get("domain") or {}
categories = domain.get("categories") or []
if not categories:
    print("No categories returned; send for review.")
else:
    for category in categories:
        name = category.get("name")
        if name:
            print(name, "| confidence:", category.get("confidence", "unknown"))

Both examples make one request per input URL. For production, connect their output to a durable job or decision record rather than relying on console output. Keep request failures separate from successful responses that contain no usable categories.

Read the response and map it to a policy

The following documented response shows multiple categories and additional enrichment fields for a different domain. It illustrates the shape to handle; the values are not the result of the news-domain request above.

{
    "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"
    ]
}

Start with success, then iterate over domain.categories. Each category’s name is a hierarchical path and confidence is a signal you can use in your own review policy. The sample contains two categories, so do not assume that the first is the only relevant classification.

The first sample category also has an IAB-632-596 mapping. The second does not show that field, so code that uses IAB data must tolerate its absence. Maintain an explicit mapping from the returned category or IAB value to your internal targeting taxonomy; preserve the original value in your audit record instead of storing only your translated label.

Response field Use in a targeting pipeline Handling consideration
domain.categories Match category names to campaign rules. Process all returned entries; route an empty result to review.
confidence Provide context for a rule or review decision. Choose thresholds through your own evaluation rather than treating a score as a guarantee.
IAB-632-596 Map an available IAB value to an advertising taxonomy. Do not require it on every category.
objects.company Enrich an audit or account record with company context. Allow for missing or null values; do not use company data as a substitute for content classification.
domain.logo_url and domain.social_media Add optional context to a review interface. Handle null or unavailable data without failing the category decision.

Other fields can support separate workflows. For example, objects.company.tech lists technologies, while domain_registration_data contains registration-related dates and day counts. These are not evidence that an ad placement is safe. Treat financial and date values as enrichment data, and confirm their interpretation in the documentation before using them in reporting.

Operate the integration at scale

For an ad-placement audit, collect the domains or URLs that actually appear in your inventory, classify them, and join the results back to your placement records. For an online decision, check whether a usable cached result exists before making a request. Decide in advance what happens if the API call cannot complete within your application’s latency budget.

Cache results per normalized domain when your policy operates at domain level. Store the classification time, original category values, confidence values, and the version of your internal mapping with the result. Set a refresh policy appropriate to how quickly your placements and risk tolerance change; a cached classification is a snapshot, not a permanent property of a site.

Klazify also supports URL classification, which matters when a site contains materially different sections. If your targeting decision depends on page-level content, do not silently reuse a domain-level cache entry for every path. Keep page-level and domain-level results distinct and test which scope is appropriate for the inventory you buy.

For large input sets, deduplicate domains before scheduling requests and use a queue to control concurrency. Respect the rate limits applicable to your account, and consult the documentation for current limits rather than assuming a batch size or throughput. The examples above show individual requests; build batching and scheduling in your own pipeline around that request pattern.

Handle an unknown or new domain as a separate state from a confirmed allowed category. Depending on your campaign policy, that state can mean holding the placement, sending it for human review, or applying a documented fallback. Retry transient failures through a controlled queue, but avoid treating a failed request as evidence that a site is safe.

Finally, monitor the outcomes that matter to your team: request failures, missing categories, review volume, cache age, and disagreements between classifications and human decisions. Review your mapping when campaign rules change. Failed or unreachable calls are not billed, but operational failures still need attention because they can leave placement decisions unresolved.

FAQ

Can I use the category to block an ad placement?

Yes. Match returned category names against your campaign’s block rules, then record the rule and classification behind the decision. For missing or ambiguous results, use a separate review or fallback state rather than automatically allowing the placement.

Should I classify a URL or its domain?

Use the scope that matches your policy. Domain-level results are useful for repeated inventory checks, while URL classification can provide more specific context for sites with diverse content. Keep their cached results separate.

What if a response has more than one category?

Evaluate all returned categories against your rules. Define in advance how your policy resolves a mix of allowed and blocked categories, and retain the original categories and confidence values for auditing.

What does it cost to start?

The Starter plan is $39.99 per month with a 7-day trial. Check the current plan details and applicable limits before choosing an operating model.

Register for a free account to try the categorization endpoint, then connect the response to your PHP targeting rules. For another way to work with Klazify, see MCP.

Ready to use Klazify?

Start classifying websites, enriching company data, and exploring web intelligence.

Get Started Free