How to Load XML Data into MySQL using PHP ?
Last Updated :
12 Jul, 2021
In this article, we are going to store data present in XML file into MySQL database using PHP in XAMPP server.
XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity, generality, and usability across the Internet.
Example:
HTML
<?xml version="1.0" encoding="UTF-8"?>
<datas>
<data>
<id>1</id>
<name>sravan</name>
</data>
<data>
<id>2</id>
<name>Ojaswi</name>
</data>
<data>
<id>3</id>
<name>Rohith</name>
</data>
</datas>
 Â
Loading XML file: We will use simplexml_load_file() function to convert the well-formed XML document into the given file to an object.
Â
Syntax:
Â
SimpleXMLElement simplexml_load_file( string $filename,
string $class_name = "SimpleXMLElement",
int $options = 0, string $ns = "",
bool $is_prefix = FALSE )
Â
Steps to Write and Execute code:
Â

- Identify number of attributes in xml file and create table in XAMPP. There are 4 attributes in XML file (input.xml is the file name). These are title, link. description, keywords. The database name is xmldata and table name is xml
Â
Filename: input.xml
Â
XML
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<title>PHP DATABASE CONNECTION</title>
<link>
https://www.geeksforgeeks.org/php-database-connection/
</link>
<description>
The collection of related data is called a
database. XAMPP stands for cross-platform,
Apache, MySQL, PHP, and Perl. It is among
the simple light-weight local servers for
website development.
</description>
<keywords>PHP, XAMPP</keywords>
</item>
<item>
<title>Screen density and Terminologies</title>
<link>
https://www.geeksforgeeks.org/screen-density-and-its-terminologies/
</link>
<description>
Screen Density is a calculation of the
proportion of display character positions
on the screen or an area of the screen
containing something.
</description>
<keywords>software engineering</keywords>
</item>
<item>
<title>DataProcessing vs DataCleaning</title>
<link>
https://www.geeksforgeeks.org/difference-between-data-cleaning-and-data-processing/
</link>
<description>
Data Processing: It is defined as Collection,
manipulation, and processing of collected data
for the required use. It is a task of converting
data from a given form to a much more usable and
desired form i.e. making it more meaningful and
informative. Using Machine Learning algorithms,
mathematical modelling and statistical knowledge,
this entire process can be automated. This might
seem to be simple but when it comes to really big
organizations like Twitter, Facebook,
Administrative bodies like Parliament, UNESCO and
health sector
</description>
<keywords>Data Mining</keywords>
</item>
<item>
<title>Predicting Air Quality Index</title>
<link>
https://www.geeksforgeeks.org/predicting-air-quality-index-using-python/
</link>
<description>
AQI: The air quality index is an index for
reporting air quality on a daily basis. In
other words, it is a measure of how air
pollution affects one’s health within a
short time period. The AQI is calculated
based on the average concentration of a
particular pollutant measured over a
standard time interval. Generally, the
time interval is 24 hours for most pollutants,
8 hours for carbon monoxide and ozone.
</description>
<keywords>Machine Learning, Python</keywords>
</item>
</items>
 Â
Filename: index.php
Â
PHP
<?php
// Connect to database
// Server - localhost
// Username - root
// Password - empty
// Database name = xmldata
$conn = mysqli_connect("localhost", "root", "", "xmldata");
$affectedRow = 0;
// Load xml file else check connection
$xml = simplexml_load_file("input.xml")
or die("Error: Cannot create object");
// Assign values
foreach ($xml->children() as $row) {
$title = $row->title;
$link = $row->link;
$description = $row->description;
$keywords = $row->keywords;
// SQL query to insert data into xml table
$sql = "INSERT INTO xml(title, link,
description, keywords) VALUES ('"
. $title . "','" . $link . "','"
. $description . "','" . $keywords . "')";
$result = mysqli_query($conn, $sql);
if (! empty($result)) {
$affectedRow ++;
} else {
$error_message = mysqli_error($conn) . "\n";
}
}
?>
<center><h2>GEEKS GOR GEEKS</h2></center>
<center><h1>XML Data storing in Database</h1></center>
<?php
if ($affectedRow > 0) {
$message = $affectedRow . " records inserted";
} else {
$message = "No records inserted";
}
?>
<style>
body {
max-width:550px;
font-family: Arial;
}
.affected-row {
background: #cae4ca;
padding: 10px;
margin-bottom: 20px;
border: #bdd6bd 1px solid;
border-radius: 2px;
color: #6e716e;
}
.error-message {
background: #eac0c0;
padding: 10px;
margin-bottom: 20px;
border: #dab2b2 1px solid;
border-radius: 2px;
color: #5d5b5b;
}
</style>
<div class="affected-row">
<?php echo $message; ?>
</div>
<?php if (! empty($error_message)) { ?>
<div class="error-message">
<?php echo nl2br($error_message); ?>
</div>
<?php } ?>
 Â
Execution steps:
Â
1. Save 2 files in one folder in path: xampp/htdocs/gfg
Â
Â
2. Type localhost/gfg/index.php and see the output
Â
output
Â
Now check the data in xml stored in our database or not
Â
Â
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.To better understand the foundation of web devel
7 min read