PHP AJAX XML
In this page:
header("Content-Type: text/xml");
$dom = new DOMDocument();
$root = $dom->createElement("root_name", "text");
$dom->appendChild($root);
echo $dom->saveXML();
Returning XML from a PHP Endpoint
An AJAX endpoint can build and return an XML document instead of JSON, using DOMDocument (covered in the DOM Parser topic) to construct it safely, then outputting it with the appropriate text/xml content type header.
Example: Returning XML from a PHP Endpoint
<?php
// Call `header("Content-Type: text/xml")`
header("Content-Type: text/xml");
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
// Declare `$root`, set to `$dom->createElement("response", "success")`
$root = $dom->createElement("response", "success");
$dom->appendChild($root);
// Print `$dom->saveXML()` to the output
echo $dom->saveXML();
?>
Login to try C/C++/Java/PHP code in the editor
Parsing an XML AJAX Response in JavaScript
The browser's built-in DOMParser can parse a raw XML response string into a navigable document, similar to how PHP's own DOM extension works -- response.text() retrieves the raw XML text, and new DOMParser().parseFromString() converts it into a queryable document.
Example: Parsing an XML AJAX Response in JavaScript
<?php
// JS: new DOMParser().parseFromString(await response.text(), "text/xml")
header("Content-Type: text/xml");
echo "<response>ok</response>";
?>
Login to try C/C++/Java/PHP code in the editor
Building an XML Response from Database Data
Combining a database query with XML output follows the same pattern as the JSON case -- fetch rows, then build an XML element for each one using DOMDocument, appending each row as a child element of the response document.
Example: Building an XML Response from Database Data
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE products (name TEXT)");
$db->exec("INSERT INTO products VALUES ('Book')");
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
// Declare `$root`, set to `$dom->createElement("products")`
$root = $dom->createElement("products");
// Declare `$result`, set to `$db->query("SELECT * FROM products")`
$result = $db->query("SELECT * FROM products");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Declare `$item`, set to `$dom->createElement("product", $row['name'])`
$item = $dom->createElement("product", $row['name']);
$root->appendChild($item);
}
$dom->appendChild($root);
// Print `$dom->saveXML()` to the output
echo $dom->saveXML();
?>
Login to try C/C++/Java/PHP code in the editor
Choosing Between XML and JSON for a New Endpoint
For a brand-new AJAX endpoint with no existing constraint, JSON is almost always the simpler, more efficient choice -- reach for XML specifically when integrating with a system that already expects or produces XML, not as a default starting point.
Example: Choosing Between XML and JSON for a New Endpoint
<?php
// Print "Use JSON by default; XML only when integrating with a system that already expects it" to the output
echo "Use JSON by default; XML only when integrating with a system that already expects it";
?>
Login to try C/C++/Java/PHP code in the editor
Validating an XML Response Structure
Before an AJAX endpoint's XML response is considered reliable, it is worth confirming the DOMDocument actually produces valid, well-formed XML -- calling loadXML() on the saveXML() output as a sanity check, or testing directly against the endpoint's URL and inspecting the raw response.
Example: Validating an XML Response Structure
<?php
// Create a new `DOMDocument` instance, stored in `$dom`
$dom = new DOMDocument();
// Declare `$root`, set to `$dom->createElement("response", "ok")`
$root = $dom->createElement("response", "ok");
$dom->appendChild($root);
// Declare `$xmlString`, set to `$dom->saveXML()`
$xmlString = $dom->saveXML();
// Create a new `DOMDocument` instance, stored in `$check`
$check = new DOMDocument();
// Declare `$isValid`, set to `$check->loadXML($xmlString)`
$isValid = $check->loadXML($xmlString);
// Print `$isValid ? "Well-formed XML" : "Invalid XML"` to the output
echo $isValid ? "Well-formed XML" : "Invalid XML";
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting to set the Content-Type: text/xml (or application/xml) response header, which can cause the browser or JavaScript XML parser to misinterpret the response.
- Manually concatenating XML tags around variable values as strings, risking malformed XML if a value happens to contain a character like < or & that needs escaping.
- Mixing XML and JSON response formats inconsistently across different endpoints in the same project, forcing the JavaScript to handle each one differently.
- An AJAX endpoint returning XML should set the Content-Type: text/xml header so the client correctly interprets the response.
- DOMDocument or SimpleXML should be used to build the XML response programmatically, rather than manually concatenating tag strings.
- JavaScript's fetch API can retrieve and parse an XML response with response.text() followed by the DOMParser API.
XML AJAX responses work in every modern browser via fetch() and the built-in DOMParser API; PHP's DOM and SimpleXML extensions produce standard, compliant XML.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: