Benjamin Lu

everyday is cool

A JSON Endpoint in the PHP 5.2 Era

An early Ajax request might return a fragment of HTML. JSON gives the browser a different option. The server sends named values, and the page decides how to display them. PHP 5.2 is a useful point in the timeline for this exercise because JSON support was bundled and enabled by default.

Save this as status.php on a current local PHP server:

<?php
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'ok', 'posts' => 3));

Request the file with curl -i and check the content type and the response body. Change the count, request it again, and verify that it remains a number in the response. If PHP warnings or extra markup appear before the object, fix the endpoint before wiring it into a page. A browser script should receive a clean JSON document.

PHP JSON extension installation history