• We just launched and are currently in beta. Join us as we build and grow the community.

Convert MySQL Table Data to XML Using PHP: A Step-by-Step Guide to Export Database Records

jasontsullins

Token Swap Specialist
J Rep
0
0
0
Rep
0
J Vouches
0
0
0
Vouches
0
Posts
71
Likes
52
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 250 XP
This tutorial will guide you through the systematic procedure of Exporting MySQL Database Table Records to a XML File using the PHP language. Geared towards students and PHP beginners, this guide serves as a valuable reference, offering insights to bolster their understanding and programming skills. I will present a straightforward web application that illustrates the primary objective outlined in this article.

What is XML?

eXtensible Markup Language, commonly referred to as XML, stands as a versatile markup language designed for the storage and transportation of data. Employing a set of rules that ensure both human and machine readability when encoding documents, XML's adaptability and self-descriptive characteristics have led to its widespread utilization in diverse applications. These applications include handling configuration files, facilitating data interchange between web services, and representing hierarchical data structures.

Here are some other tutorials or articles that are related in XML:

  • PHP - Insert New Entry In XML File
  • PHP - Update Data in XML File
  • PHP - Simple Upload XML File to MySQLi

Explore the XML-related topics listed above by clicking on them to be redirected to their dedicated articles for a more in-depth understanding.

How to Export MySQL Database Table Records into XML File?

Before getting started, please download and install the following software on your local machine if they are not already installed:

  • XAMPP/WAMP or any equivalent local web and MySQL server software
  • Code Editor such as Notepad++, Sublime Text, and MS VS Code

After successfully installing the aforementioned requirements, ensure that you have started the Apache

and MySQL

servers. In XAMPP/WAMP, open their control panel and click the start buttons for the mentioned servers. The status of each server will be displayed in the control panel logs.

Let's Get Started

Step 1: Let's Create the Database and the Table

Initial steps involve creating the Database for our sample web application. Open PHPMyAdmin and navigate to the SQL

page. Confirm that the dummy_db

database name is still accessible in your MySQL. Utilize or refer to the MySQL script below for the creation of the database, table, and columns:

  1. --
  2. -- Database: `dummy_db`
  3. --
  4. CREATE

    DATABASE

    [url=http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html]IF

    NOT

    EXISTS

    [/url] `dummy_

    db`

    DEFAULT

    CHARACTER SET

    utf8mb4 COLLATE

    utf8mb4_general_ci;
  5. USE

    `dummy_

    db`

    ;

  6. -- --------------------------------------------------------

  7. --
  8. -- Table structure for table `members`
  9. --

  10. CREATE

    TABLE

    [url=http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html]IF

    NOT

    EXISTS

    [/url] `members`

    (
  11. `id`

    int

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  12. `name`

    varchar

    (

    255

    )

    DEFAULT

    NULL

    ,
  13. `username`

    varchar

    (

    50

    )

    DEFAULT

    NULL

    ,
  14. `email`

    varchar

    (

    100

    )

    DEFAULT

    NULL

    ,
  15. `contact_

    no`

    varchar

    (

    15

    )

    DEFAULT

    NULL

    ,
  16. PRIMARY KEY

    (

    `id`

    )

    ,
  17. UNIQUE

    KEY

    `username`

    (

    `username`

    )

    ,
  18. UNIQUE

    KEY

    `email`

    (

    `email`

    )
  19. )

    ENGINE

    =

    InnoDB

    AUTO_INCREMENT

    =

    11

    DEFAULT

    CHARSET

    =

    utf8mb4 COLLATE

    =

    utf8mb4_general_ci;

  20. --
  21. -- Dumping data for table `members`
  22. --

  23. INSERT

    INTO

    `members`

    (

    `id`

    ,

    `name`

    ,

    `username`

    ,

    `email`

    ,

    `contact_

    no`

    )

    VALUES


  24. (

    1

    ,

    'John Doe'

    ,

    'johndoe'

    ,

    '[email protected]'

    ,

    '123-456-7890'

    )

    ,
  25. (

    2

    ,

    'Jane Smith'

    ,

    'janesmith'

    ,

    '[email protected]'

    ,

    '987-654-3210'

    )

    ,
  26. (

    3

    ,

    'Bob Johnson'

    ,

    'bobjohnson'

    ,

    '[email protected]'

    ,

    '555-123-4567'

    )

    ,
  27. (

    4

    ,

    'Alice Brown'

    ,

    'alicebrown'

    ,

    '[email protected]'

    ,

    '789-456-1230'

    )

    ,
  28. (

    5

    ,

    'Charlie Wilson'

    ,

    'charliewilson'

    ,

    '[email protected]'

    ,

    '555-789-0123'

    )

    ,
  29. (

    6

    ,

    'Eva Garcia'

    ,

    'evagarcia'

    ,

    '[email protected]'

    ,

    '123-789-4560'

    )

    ,
  30. (

    7

    ,

    'David Lee'

    ,

    'davidlee'

    ,

    '[email protected]'

    ,

    '456-123-7890'

    )

    ,
  31. (

    8

    ,

    'Emily Davis'

    ,

    'emilydavis'

    ,

    '[email protected]'

    ,

    '789-012-3456'

    )

    ,
  32. (

    9

    ,

    'Frank Miller'

    ,

    'frankmiller'

    ,

    '[email protected]'

    ,

    '012-345-6789'

    )

    ,
  33. (

    10

    ,

    'Grace Turner'

    ,

    'graceturner'

    ,

    '[email protected]'

    ,

    '987-654-3210'

    )

    ;

Executing the provided MySQL script will yield a result similar to the image below:

Step 2: Creating the Database Connection

Moving forward, let's generate the PHP file containing the scripts that establish a connection between our PHP web application and the MySQL Database. To accomplish this, create a new PHP file within your web application's source code directory and open it with your preferred code editor. Save the file as `db-connect.php

`. Consult the following PHP script for composing the database connection script in PHP:

  1. <?php
  2. // DB Hostname
  3. $host

    =

    "localhost"

    ;
  4. // DB username
  5. $uname

    =

    "root"

    ;
  6. // DB password
  7. $pw

    =

    ""

    ;
  8. // DB Name
  9. $dbName

    =

    "dummy_db"

    ;

  10. try{
  11. // Opening Database Connection
  12. $conn

    =

    new

    MySQLi(

    $host

    ,

    $uname

    ,

    $pw

    ,

    $dbName

    )

    ;
  13. }

    catch(

    Exception $e

    )

    {
  14. // Opening Database Connection Failed
  15. echo

    "Database connection Error:\n

    <br>\n

    "

    ;
  16. print_r

    (

    $e

    ->

    getMessage

    (

    )

    )

    ;
  17. exit

    ;
  18. }

Ensure to replace the variable values with the correct database credentials in the script above on your end.

Step 3: Creating Web Application Page Interface

Now, let's establish the page interface for our sample web application. Create a new PHP file named `index.php

`. This file contains a combined PHP and HTML scripts, relevant for the page interface that displays the retrieved database records. It also incorporates the PHP script responsible for retrieving records from the database and includes the PHP file for data export or transformation.

Note that the script includes CDN links for loading the Bootstrap Framework and jQuery Library. Therefore, an internet connection is necessary for the expected page design to load when browsing the page.

  1. <?php
  2. // Start Session
  3. session_start

    (

    )

    ;
  4. // Require Database Connection File
  5. require_once

    (

    "db-connect.php"

    )

    ;

  6. /**
  7. * Retrieve Members Data from MySQL Database
  8. */
  9. // SQL Statement
  10. $members_sql

    =

    "SELECT * FROM `members` order by id asc"

    ;
  11. // SQL Query
  12. $members_qry

    =

    $conn

    ->

    query

    (

    $members_sql

    )

    ;
  13. // SQL Execution and storing retrive data in a variable
  14. $members

    =

    $members_qry

    ->

    fetch_all

    (

    MYSQLI_ASSOC)

    ;

  15. /**
  16. * Including the PHP file that contains the Script that Exports MySQL Data into XML File
  17. */
  18. if

    (

    isset

    (

    $_GET

    [

    'action'

    ]

    )

    &&

    $_GET

    [

    'action'

    ]

    ==

    'export_as_xml'

    )

    {
  19. include_once

    (

    "export_as_xml.php"

    )

    ;
  20. }


  21. ?>
  22. <!DOCTYPE html>
  23. <html lang="en">
  24. <head>
  25. <meta charset="UTF-8">
  26. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  27. <title>Create XML from MySQL Data</title>
  28. <!-- Bootstrap 5.3 CSS-->
  29. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  30. <!-- jQuery -->
  31. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  32. <!-- Bootstrap 5.3 JS-->
  33. <script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  34. </head>
  35. <body>
  36. <nav class="navbar navbar-expand-lg bg-body-tertiary">
  37. <div class="container-fluid">
  38. <a class="navbar-brand" href="#">Create XML From MySQL Data</a>
  39. <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  40. <span class="navbar-toggler-icon"></span>
  41. </button>
  42. <div class="collapse navbar-collapse" id="navbarNav">
  43. <ul class="navbar-nav">
  44. <li class="nav-item">
  45. <a class="nav-link <?=

    $page

    ==

    'home'

    ? "active"

    :

    ''

    ?>

    " href="./">Home</a>
  46. </li>
  47. </ul>
  48. </div>
  49. </div>
  50. </nav>
  51. <div class="container-md py-4">
  52. <!-- Flashdata -->
  53. <?php

    if

    (

    isset

    (

    $_SESSION

    [

    'flashdata'

    ]

    )

    &&

    !

    empty

    (

    $_SESSION

    [

    'flashdata'

    ]

    )

    )

    :

    ?>
  54. <div class="alert alert-<?=

    $_SESSION

    [

    'flashdata'

    ]

    [

    'type'

    ]

    ?>

    px-2 py-1 rounded-0">
  55. <?=

    $_SESSION

    [

    'flashdata'

    ]

    [

    'msg'

    ]

    ?>
  56. </div>
  57. <?php

    unset

    (

    $_SESSION

    [

    'flashdata'

    ]

    )

    ;

    ?>
  58. <?php

    endif

    ;

    ?>
  59. <!-- End of Flashdata -->

  60. <div class="card rounded-0 mx-auto col-lg-9 col-md-10 col-sm-12 col-12">
  61. <div class="card-header rounded-0">
  62. <div class="d-flex w-100 justify-content-between align-items-center">
  63. <h5 class="card-title col-auto flex-grow-1">Sample Site Member List</h5>
  64. <div class="col-auto flex-shrink-1">
  65. <a href="./?action=export_as_xml" class="btn btn-sm btn-primary border rounded-0">Export Data to XML File</a>
  66. </div>
  67. </div>
  68. </div>
  69. <div class="card-body rounded-0">
  70. <div class="container-fluid">
  71. <!-- Displaying MySQL Data into Table Element -->
  72. <div class="table-responsive">
  73. <table class="table table-bordered table-hover table-striped">
  74. <colgrep>
  75. <col width="10%">
  76. <col width="30%">
  77. <col width="20%">
  78. <col width="20%">
  79. <col width="20%">
  80. </colgrep>
  81. <thead>
  82. <tr class="bg-gradient bg-primary">
  83. <th class="text-center bg-transparent text-light">ID</th>
  84. <th class="text-center bg-transparent text-light">Name</th>
  85. <th class="text-center bg-transparent text-light">Username</th>
  86. <th class="text-center bg-transparent text-light">Email</th>
  87. <th class="text-center bg-transparent text-light">Contact No.</th>
  88. </tr>
  89. </thead>
  90. <tbody>
  91. <?php

    if

    (

    !

    empty

    (

    $members

    )

    )

    :

    ?>
  92. <?php

    foreach

    (

    $members

    as

    $member

    )

    :

    ?>
  93. <tr>
  94. <td class="text-center px-2 py-1"><?=

    $member

    [

    'id'

    ]

    ?>

    </td>
  95. <td class="px-2 py-1"><?=

    $member

    [

    'name'

    ]

    ?>

    </td>
  96. <td class="px-2 py-1"><?=

    $member

    [

    'username'

    ]

    ?>

    </td>
  97. <td class="px-2 py-1"><?=

    $member

    [

    'email'

    ]

    ?>

    </td>
  98. <td class="px-2 py-1"><?=

    $member

    [

    'contact_no'

    ]

    ?>

    </td>
  99. </tr>
  100. <?php

    endforeach

    ;

    ?>
  101. <?php

    endif

    ;

    ?>
  102. </tbody>
  103. </table>
  104. </div>
  105. <!-- End of Displaying MySQL Data into Table Element -->
  106. </div>
  107. </div>
  108. </div>
  109. </div>
  110. <?php
  111. // Closing Database Connection
  112. if

    (

    $conn

    )
  113. $conn

    ->

    close

    (

    )

    ;
  114. ?>
  115. </body>
  116. </html>

Step 3: Creating Main PHP Script

Finally, let's craft the PHP file housing the script responsible for generating XML content from the MySQL Database Table Records. Create a new PHP file named `export_as_xml.php

`. This file contains the script utilizing the DOMDocument

built-in class in PHP.

The DOMDocument class is a component of the Document Object Model (DOM) extension in PHP. It offers a method to represent an entire document, be it HTML or XML, as an Object-Oriented tree structure. In this structure, each node corresponds to a component of the document, such as elements, attributes, or text.

  1. <?php
  2. if

    (

    !

    empty

    (

    $members

    )

    )

    {
  3. // Creating a new DOMDocument
  4. $xml

    =

    new

    DOMDocument(

    )

    ;
  5. // Creating the Root Element
  6. $membersEl

    =

    $xml

    ->

    createElement

    (

    'members'

    )

    ;

  7. // Looping Members Row
  8. foreach

    (

    $members

    as

    $member

    )

    {
  9. // Creating Member Row Element and adding it into the root Element
  10. $newMemberRow

    =

    $membersEl

    ->

    appendChild

    (

    $xml

    ->

    createElement

    (

    'member'

    )

    )

    ;

  11. foreach

    (

    $member

    as

    $field

    =>

    $value

    )

    {
  12. // Creating the Memeber's Info Field Name and Value Element and adding it to the current memeber row's element
  13. $newMemberRow

    ->

    appendChild

    (

    $xml

    ->

    createElement

    (

    $field

    ,

    $value

    )

    )

    ;
  14. }
  15. }
  16. // adding the root Members Element with the child member elements into the created document
  17. $xml

    ->

    appendChild

    (

    $membersEl

    )

    ;
  18. // Nicely printing the format of the output with indentions
  19. $xml

    ->

    formatOutput

    =

    true

    ;
  20. // Save in new or overwrite existing XML file with the current XML File Content
  21. $xml

    ->

    save

    (

    "members.xml"

    )

    ;


  22. // Storing a Success Flash Message to display in the UI
  23. $_SESSION

    [

    'flashdata'

    ]

    =

    [
  24. "type"

    =>

    "success"

    ,
  25. "msg"

    =>

    "Members Data has been successfully exported in XML File"
  26. ]

    ;


  27. }

    else

    {
  28. // members data is empty

  29. // Storing Error Flash Message to display in the UI
  30. $_SESSION

    [

    'flashdata'

    ]

    =

    [
  31. "type"

    =>

    "danger"

    ,
  32. "msg"

    =>

    "Members Data is Empty"
  33. ]

    ;
  34. }
  35. // reloading the page using location.replace JS script to remove the provided GET request data
  36. echo

    "<script>location.replace('./');</script>"

    ;
  37. die

    (

    )

    ;
  38. ?>

Upon executing the provided scripts, clicking the `Export Data to XML File

` button above the table in the page interface will initiate the export of MySQL database table records into an XML file. Upon successful completion of the process, a confirmation message will be displayed, as shown in the image below:

The resulting exported XML file will be named `members.xml

`, containing content similar to the following:

I've also included the complete compressed source code file of the provided scripts on this website. You can download it by clicking the Download

button located below this tutorial article.

And that's it! I hope this PHP Tutorial on Exporting MySQL Database Records into XML Files proves beneficial, aiding you in your PHP projects. Explore further on this website for additional Free Source Codes, Tutorials, and Articles spanning various programming languages.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

442,401

317,942

317,951

Top