PHP Example – AJAX and XML Tutorial

PHP Example – AJAX and XML Complete Tutorial

Before JSON became popular, XML was the most commonly used format for AJAX responses. Even today, XML is still used in many legacy systems, APIs, and enterprise applications.

This tutorial explains how to use AJAX with XML in PHP, showing how PHP generates XML data and how AJAX reads and displays it without reloading the page.


What Is AJAX and XML in PHP?

  • AJAX sends asynchronous requests from the browser
  • XML is a structured data format
  • PHP generates or processes XML on the server

AJAX + XML allows the browser to fetch structured data from PHP and update part of a webpage dynamically.


Why Use XML with AJAX in PHP?

Using XML is useful when:

  • Working with legacy systems
  • Integrating SOAP-based APIs
  • Handling structured hierarchical data
  • Learning core AJAX concepts

How AJAX Works with XML in PHP

Flow:

  1. JavaScript sends AJAX request
  2. PHP processes request
  3. PHP generates XML response
  4. JavaScript reads XML
  5. Webpage updates content

Prerequisites for AJAX XML Tutorial

Before starting, you should know:

  • Basic HTML
  • Basic JavaScript
  • PHP fundamentals
  • How PHP runs on a server

Example Scenario for AJAX and XML

We will:

  • Request user data using AJAX
  • PHP will return data in XML format
  • JavaScript will parse XML and display it

Step 1: XML Data Generated by PHP

Create a PHP file named data.php

<?php
header("Content-Type: text/xml");

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo "<users>";

echo "<user>";
echo "<name>Rahul</name>";
echo "<email>rahul@gmail.com</email>";
echo "</user>";

echo "<user>";
echo "<name>Amit</name>";
echo "<email>amit@gmail.com</email>";
echo "</user>";

echo "</users>";
?>

Step 2: HTML and AJAX JavaScript Code

Create index.html

<!DOCTYPE html>
<html>
<head>
    <title>AJAX XML Example</title>
    <script>
        function loadXML() {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "data.php", true);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var xml = xhr.responseXML;
                    var users = xml.getElementsByTagName("user");
                    var output = "";

                    for (var i = 0; i < users.length; i++) {
                        var name = users[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
                        var email = users[i].getElementsByTagName("email")[0].childNodes[0].nodeValue;

                        output += name + " - " + email + "<br>";
                    }

                    document.getElementById("result").innerHTML = output;
                }
            };

            xhr.send();
        }
    </script>
</head>
<body>

<button onclick="loadXML()">Load XML Data</button>
<div id="result"></div>

</body>
</html>

Output on Button Click

Rahul - rahul@gmail.com
Amit - amit@gmail.com

The page loads XML data without refreshing.


Example: AJAX XML with PHP and MySQL

PHP can also generate XML from a database.

<?php
header("Content-Type: text/xml");
include "db.php";

echo "<?xml version='1.0' encoding='UTF-8'?>";
echo "<users>";

$result = mysqli_query($conn, "SELECT * FROM users");

while ($row = mysqli_fetch_assoc($result)) {
    echo "<user>";
    echo "<name>".$row['name']."</name>";
    echo "<email>".$row['email']."</email>";
    echo "</user>";
}

echo "</users>";
?>

Difference Between XML and JSON in AJAX

FeatureXMLJSON
ReadabilityVerboseLightweight
ParsingSlowerFaster
PopularityDecliningVery high
StructureTag-basedKey-value

PHP AJAX XML example, AJAX and XML PHP tutorial, PHP XML AJAX, PHP AJAX XML response, AJAX XML parsing PHP


Common Mistakes When Using AJAX XML

  • Forgetting Content-Type header
  • Incorrect XML structure
  • Not using responseXML
  • Parsing text instead of XML

Best Practices for AJAX and XML in PHP

  • Always set correct headers
  • Validate XML structure
  • Escape special characters
  • Use XML only when required
  • Prefer JSON for modern apps

Related tutorial:


Frequently Asked Questions (FAQ)

1. Is XML still used with AJAX?

Yes, mainly in legacy and enterprise systems.

2. Which is better, XML or JSON?

JSON is better for modern applications.

3. Can PHP generate XML?

Yes, easily using echo or DOM functions.

4. How does JavaScript read XML?

Using responseXML property.

5. Does XML work without database?

Yes, XML can be static or dynamic.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Prove your humanity: 10   +   2   =