Content Negotiation Demo

This page returns HTML for browsers, but JSON for API clients.

User List (HTML View)

ID Name Email
1 Alice alice@example.com
2 Bob bob@example.com
3 Charlie charlie@example.com

Generated at: 2026-02-04T02:56:48+00:00

Try Getting JSON

View as JSON View as HTML

Your Accept Header

*/*

Testing with curl

# Default (no Accept header) - returns HTML
curl http://localhost:8000/php-tutorial/03-headers/content-negotiation.php

# Request JSON explicitly
curl -H "Accept: application/json" http://localhost:8000/php-tutorial/03-headers/content-negotiation.php

# Using query parameter
curl "http://localhost:8000/php-tutorial/03-headers/content-negotiation.php?format=json"

The PHP Code

<?php
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';

// Check if client wants JSON
$wantsJson = strpos($accept, 'application/json') !== false;

// Also support ?format=json
if (isset($_GET['format']) && $_GET['format'] === 'json') {
    $wantsJson = true;
}

if ($wantsJson) {
    header('Content-Type: application/json');
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;  // Don't output HTML
}

// Otherwise output HTML...
?>

Why Content Negotiation?


Previous: Request Inspector | Back to Module | Next: Raw Body