How to populate MySQL DB from $xml defined as follows?
$xml = simplexml_load_string($line);
Is there any predefine function that automates some parts of this job? Or do I need to use DOM?
I think this should work. I have used the following code, and worked well for me. This code not only adds data for one xml file but can be used for multiple xml files.
<?php
// table headers --> SNo Field Value
$connection = mysql_connect("localhost","root","password");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("forms_data",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
mysql_query("CREATE table form_try11(id int(11) not null auto_increment,
Field varchar(100),
Value varchar(100),
primary key(id)
)");
$file1="C:\webserver\Apache\htdocs\php_json\file1.xml";
$file2="C:\webserver\Apache\htdocs\php_json\file2.xml";
$file3="C:\webserver\Apache\htdocs\php_json\file3.xml";
$path_arr = Array($file1,$file2,$file3);
for($count1=0; $count1<count($path_arr); $count1++){
$xml = simplexml_load_file($path_arr[$count1]);
$string= json_encode($xml);
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($string, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val) || $key=="xmlns:xfa" || $key=="xfa:dataNode") {
continue;
}
else {
$db_insert= mysql_query("INSERT INTO form_try11(Field,Value) VALUES('$key','$val') ");
if (!$db_insert) {
die("Database insert failed: " . mysql_error());
}
}
}
}
mysql_close($connection);
?>
No predefined functions that I know of, but you can do the following:
See all the variables using
var_dump($xml);
And then do a loop to insert them into the database like this:
foreach($xml as $element)
{
$PDO->prepare('INSERT .....');
$PDO->bindParam(blah,blah);
$PDO->execute()
}
If you are trying to pull all file to a table, You can import it using SQL statements.
LOAD XML LOCAL INFILE 'your_xml_file.xml'
INTO TABLE your_table_name(field_one,field_two,....);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.