PHP Classes

File: index.php

Recommend this page to a friend!
  Classes of Ahmed Abdulla   PHP MySQL XML Output   index.php   Download  
File: index.php
Role: Application script
Content type: text/plain
Description: Main Page
Class: PHP MySQL XML Output
Output XML from MySQL query results
Author: By
Last change:
Date: 8 months ago
Size: 1,286 bytes
 

Contents

Class file image Download
<?php
// Database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die(
"Connection failed: " . $conn->connect_error);
}

// Create an XML document
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;

// Create a root element
$root = $xml->createElement('database');
$xml->appendChild($root);

// Select data from the database
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

if (
$result->num_rows > 0) {
    while (
$row = $result->fetch_assoc()) {
       
// Create a child element for each row
       
$rowElement = $xml->createElement('row');
       
$root->appendChild($rowElement);

       
// Add data as child elements to the row
       
foreach ($row as $column => $value) {
           
$columnElement = $xml->createElement($column, $value);
           
$rowElement->appendChild($columnElement);
        }
    }
}

// Save the XML to a file or output it to the browser
$xmlString = $xml->saveXML();
echo
$xmlString;

// Close the database connection
$conn->close();
?>