php code to read xml value and save to mysql
Posted: Mon Mar 09, 2009 1:35 am
xml file
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User>
<Name>a</Name>
<Password>b</Password>
</User>
<User>
<Name>c</Name>
<Password>d</Password>
</User>
<User>
<Name>e</Name>
<Password>f</Password>
</User>
</Users>
Database name: sample
table name:users
CREATE TABLE IF NOT EXISTS `users` (
`name` varchar(500) NOT NULL,
`password` varchar(500) NOT NULL
)
<?php
//Read the xml file
$myFile = "r.xml";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
/*
* Load the xml into simplexml object
*/
$xml = simplexml_load_string($theData);
/*
* This is beginning for mysql query string
*/
$sql = "INSERT INTO users (name, password) VALUES ";
$stack = array();
/*
* Insert formated values from xml into second part of sql query
*/
foreach ($xml as $user) {
$stack[] = "('{$user->Name}', '{$user->Password}')";
}
/*
* Implde array of values from xml to sql query
*/
$sql .= implode(', ', $stack);
/*
* Connection to databaze server
*/
if (!mysql_connect('localhost', 'root', ''))
die(mysql_error());
/*
* Selecting a databaze on mysql server
*/
if (!mysql_select_db('sample'))
die(mysql_error());
/*
* Inserting data into mysql databaze
*/
if (!mysql_query($sql))
die(mysql_error());
echo "Database successful updated";
echo "Created By Ramanathan.V,Chennai,India";
?>
Regards
Ramanathan.V
Chennai
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User>
<Name>a</Name>
<Password>b</Password>
</User>
<User>
<Name>c</Name>
<Password>d</Password>
</User>
<User>
<Name>e</Name>
<Password>f</Password>
</User>
</Users>
Database name: sample
table name:users
CREATE TABLE IF NOT EXISTS `users` (
`name` varchar(500) NOT NULL,
`password` varchar(500) NOT NULL
)
<?php
//Read the xml file
$myFile = "r.xml";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
/*
* Load the xml into simplexml object
*/
$xml = simplexml_load_string($theData);
/*
* This is beginning for mysql query string
*/
$sql = "INSERT INTO users (name, password) VALUES ";
$stack = array();
/*
* Insert formated values from xml into second part of sql query
*/
foreach ($xml as $user) {
$stack[] = "('{$user->Name}', '{$user->Password}')";
}
/*
* Implde array of values from xml to sql query
*/
$sql .= implode(', ', $stack);
/*
* Connection to databaze server
*/
if (!mysql_connect('localhost', 'root', ''))
die(mysql_error());
/*
* Selecting a databaze on mysql server
*/
if (!mysql_select_db('sample'))
die(mysql_error());
/*
* Inserting data into mysql databaze
*/
if (!mysql_query($sql))
die(mysql_error());
echo "Database successful updated";
echo "Created By Ramanathan.V,Chennai,India";
?>
Regards
Ramanathan.V
Chennai