bhylu.com

Advertisements

XML Server-side XML

A server can read records from a database and serialize a safe XML response. Keep database queries and XML construction as separate operations.

How it works

This complete PHP CLI lab uses an in-memory SQLite database with fictional rows. DOMDocument creates element and text nodes so an ampersand cannot become markup. A real HTTP endpoint should set Content-Type: application/xml; charset=UTF-8 before writing bytes, check authorization and handle database failures. Classic ASP is a different legacy server runtime; it is not executed by PHP or by the browser, and the course does not pretend that an ASP snippet was tested here.

Run the code

Use PHP 8.2+ with DOM, PDO and pdo_sqlite. Run php server-serialization.php in an empty local lab. This is a CLI serialization example using an in-memory database, not a deployed HTTP endpoint.

Download the complete server-serialization.php source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.

Example

server-serialization.php

<?php
declare(strict_types=1);
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE packet (id TEXT, name TEXT)');
$insert = $db->prepare('INSERT INTO packet VALUES (?, ?)');
$insert->execute(['p4', 'Peas & beans']);
$document = new DOMDocument('1.0', 'UTF-8');
$root = $document->appendChild($document->createElement('exchange'));
foreach ($db->query('SELECT id, name FROM packet ORDER BY id') as $row) {
    $packet = $root->appendChild($document->createElement('packet'));
    $packet->setAttribute('id', $row['id']);
    $packet->appendChild($document->createTextNode($row['name']));
}
echo $document->saveXML($document->documentElement), PHP_EOL;

Expected result

<exchange><packet id="p4">Peas &amp; beans</packet></exchange>

Run the source with PHP 8.2+ and the DOM, PDO and pdo_sqlite extensions. The query is deterministic and the database disappears when the process ends. This review proves CLI serialization, not Apache routing, authentication or an ASP deployment.

Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.