PHP Import XML File Into Database |
X

Congrats, You are Subscribed to Receive Updates.

PHP Import XML File Into Database


Introduction

PHP Import XML File Into Database is my another article to handle the exported XML file and import it on to  another MySQL database. In my Previous Article, I wrote about how to Generate XML File Using PHP And MySQL.

After Creating XML from your database.  You can carry the file to another host or another server to process the import and get the same data in that server.  Let’s code the Import operations with the same example Program, I have used in my previous Article.

Read XML File

With the help of following code, you can read the xml file and store all the content on to a string.

$string = file_get_contents('rss.xml');

We can Parse it with SimpleXMLElement. That’s it.

PHP-Import-XML-File-Into-Database

Import the XML File Into  Database

We can use for loop to iterate the content and import it into database. Here is the code to understand.

$xml = new SimpleXMLElement($string);
foreach($xml->users->user as $item){
    echo $item->ID.' - ';
    echo $item->username.' - ';
    echo $item->email.' - ';
    echo '<br/>';
    mysqli_query($conn, "INSERT INTO users (ID, username ,email ) VALUES (". $item->ID.", '". $item->username."', '" .$item->email."')" );
}

And if you prefer to get a single value from it. Just use it like this.

$xml = new SimpleXMLElement($string);
echo 'Reading Single Value: -'. $xml->users->user[0]->username; // get single value

That’s it. Also one more thing, if your ID has an existing value in the database, The query may failed to insert such a content.  So Avoid importing Auto-increment Values.

Here is my full code for the import

<?php
$string = file_get_contents('rss.xml');
$xml = new SimpleXMLElement($string);
echo 'Reading Single Value: -'. $xml->users->user[0]->username; // get single value
echo '<br /><br />';
//Loop trough multiple Items
echo 'All Values of a Group: -';
foreach($xml->users->user as $item){
    echo $item->ID.' - ';
    echo $item->username.' - ';
    echo $item->email.' - ';
    echo '<br/>';
    mysqli_query($conn, "INSERT INTO users (ID, username ,email ) VALUES (". $item->ID.", '". $item->username."', '" .$item->email."')" );
}
?>

If you like my articles subscribe my feeds and also follow me on social sites to get more updates from my forth writing articles.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

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

*

Current ye@r *

Menu

Sidebar