Home Backend Development PHP Tutorial Import XML data into database using PHP

Import XML data into database using PHP

Aug 07, 2023 am 09:58 AM
php xml database

Use PHP to import XML data into the database

Introduction:
During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database.

Step 1: Parse the XML file
First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using the SimpleXML extension. The following is a simple XML file example:

<data>
  <item>
    <name>Item 1</name>
    <price>19.99</price>
  </item>
  <item>
    <name>Item 2</name>
    <price>29.99</price>
  </item>
  <item>
    <name>Item 3</name>
    <price>39.99</price>
  </item>
</data>
Copy after login

We can parse and output the data in the XML file through the following code:

$xml = simplexml_load_file('data.xml');
foreach ($xml->item as $item) {
    echo 'Name: ' . $item->name . ', Price: ' . $item->price . '<br>';
}
Copy after login

Run the above code, the following results will be output:

Name: Item 1, Price: 19.99
Name: Item 2, Price: 29.99
Name: Item 3, Price: 39.99
Copy after login

Step 2: Connect to the database
Next, we need to connect to the database and create a table to store the data we parse. It is assumed here that we use the MySQL database as an example.

$host = 'localhost';
$db = 'database';
$user = 'username';
$pass = 'password';

// 连接到数据库
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die('连接数据库失败:' . $conn->connect_error);
}

// 创建表(如果不存在)
$sql = "CREATE TABLE IF NOT EXISTS items (
    name VARCHAR(100) NOT NULL,
    price DECIMAL(10, 2) NOT NULL
)";
if ($conn->query($sql) !== true) {
    die('创建表失败:' . $conn->error);
}
Copy after login

Step 3: Insert data
Now we can insert the parsed data into the table in the database.

foreach ($xml->item as $item) {
    $name = $conn->real_escape_string($item->name);
    $price = (float) $item->price;
    
    // 插入记录
    $sql = "INSERT INTO items (name, price) VALUES ('$name', '$price')";
    if ($conn->query($sql) !== true) {
        echo '插入记录失败:' . $conn->error;
    }
}

// 关闭数据库连接
$conn->close();
Copy after login

Finally, we need to read the data in the XML file line by line and insert it into the database table. During the insertion process, we used real_escape_string to escape special characters to prevent injection attacks. At the same time, we also processed the price field and converted it to floating point format.

Summary:
This article introduces how to use PHP to import XML data into the database. First, we use the SimpleXML extension to parse the XML file and extract the required data. Then, we connect to the database, create the table, and finally insert the data into the table. This process can be easily used to import external data into the database, providing convenience for subsequent data processing and analysis.

Reference:

  • [PHP: SimpleXML](https://www.php.net/manual/en/book.simplexml.php)
  • [PHP: mysqli](https://www.php.net/manual/en/book.mysqli.php)

More code examples:

  • [ GitHub repository](https://github.com/example-repo)

The above is the detailed content of Import XML data into database using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

See all articles