2012-05-24 29 views
1

我正在处理XML文件,我需要通过PHP读取数据,然后将数据保存到数据库中。到目前为止,我成功了。问题是,它是专门为下面的XML制作的。我需要的是一个通用的代码,它可以对任何类型的XML代码执行相同的操作。从XML捕获数据并保存在数据库中

这是我的XML和PHP代码

<?xml version="1.0" encoding="ISO-8859-1"?> 

<list> 

<person> 

     <person_id>1</person_id> 
     <fname>Mikael</fname> 
     <lname>Ronstrom</lname> 
    </person> 
    <person> 
     <person_id>2</person_id> 
     <fname>Lars</fname> 
     <lname>Thalmann</lname> 
    </person> 
    <person> 
     <person_id>3</person_id> 
     <fname>Mikael</fname> 
     <lname>Ronstrom</lname> 
    </person> 
    <person> 
     <person_id>4</person_id> 
     <fname>Lars</fname> 
     <lname>Thalmann</lname> 
    </person> 
    <person> 
     <person_id>5</person_id> 
     <fname>Mikael</fname> 
     <lname>Ronstrom</lname> 
    </person> 
    <person> 
     <person_id>6</person_id> 
     <fname>Lars</fname> 
     <lname>Thalmann</lname> 

    </person> 
</list> 

这里是我的PHP代码

$con = mysql_connect("localhost","root","vertrigo"); 
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("test", $con); 



$xml = simplexml_load_file("xml.xml"); 


$aa = ""; 
foreach($xml->children() as $child) 
{ 


foreach($child->children() as $childs) 
{ 
$aa .= "'".$childs ."',"; 


} 
$aa = substr_replace($aa, "", -1); 

$sql = "INSERT into tbl_xmldata (person_id,first_name,last_name) values ($aa)"; 
$aa = ""; 
$rr = mysql_query($sql); 

} 
if ($rr){ echo "data successfully captured from XML and inserted in db";}else{ echo "sorry no data insertion";} 
+0

有没有人可以帮助我? – user1210460

+3

如果不进行某些高级编程,你所要求的声音几乎是不可能的。一个数据库有一个预定义的结构 - 表,列,字段类型等,所以导入“任何”类型的XML意味着你将不得不建立一些高级函数,以便动态地建立数据库结构,这样您的PHP脚本可以正确地将数据插入到该数据库中的正确位置。 – GDP

回答

3

更新:

在互联网上搜索,我发现这个类,也许可以帮助你:

它是calle d MySQL把XML - XML到MySQL并插入MySQL中XML和出口的MySQL到XML

链接:http://www.phpclasses.org/package/782-PHP-Insert-XML-in-MySQL-and-export-MySQL-to-XML.html


第一个想法:

中有人的评论说:您的问题:

“数据库具有预定义的结构 - 表,列,字段类型等,因此要导入”一个y“种类的XML意味着您将不得不建立一些高级功能,以便动态构建数据库结构,以便您的PHP脚本可以正确地将数据插入到该数据库中的正确位置。”

他是对的,这几乎是不可能的。我的建议是使用一个类来解析XML。这个类将XML转换为$array,然后您可以获得您想要的任何元素(我认为您可以做的最好)。

下载PHP级 “洁净XML到阵列” 在这里:

http://dl.dropbox.com/u/15208254/stackoverflow/lib.xml.php

例子:

<?php 

header('Content-type: text/plain'); 

include('lib.xml.php'); 

$xml = new Xml; 


// PARSE 


// Parse from a source into a variable (default source type : FILE) 
$source = '<?xml version="1.0" encoding="utf-8"?> 

<test> 
    <this a="b"> 
    <is c="d"> 
     <a e="f" g="h"> first test</a> 
    </is> 
    <is> 
     <b hello="world">second test</b> 
    </is> 
    </this> 
</test>'; 
$out = $xml->parse($source, NULL); 
print_r($out); 

/* will output 
Array 
( 
    [this] => Array 
     ( 
      [is] => Array 
       ( 
        [0] => Array 
         ( 
          [a] => first test 
          [a-ATTR] => Array 
           ( 
            [e] => f 
            [g] => h 
           ) 
         ) 
        [1] => Array 
         ( 
          [b] => second test 
          [b-ATTR] => Array 
           ( 
            [hello] => world 
           ) 
         ) 
       ) 
      [is-ATTR] => Array 
       ( 
        [c] => d 
       ) 
     ) 
    [this-ATTR] => Array 
     ( 
      [a] => b 
     ) 
) 
*/ 


// Parse from a local file 
$out = $xml->parse('myfile.xml', 'FILE'); 
print_r($out); 

// Parse from a Web file 
$out = $xml->parse('http://site.tld/myfile.xml', 'CURL'); 
print_r($out); 



// ENCODING 

// You could specify an encoding type (default : utf-8) 
$out = $xml->parse('myfile.xml', 'FILE', 'ISO-8859-15'); 
print_r($out); 

// have fun ;-) 

?> 

如何插入值是多少?

做一个重复元素的for each,否则访问其他元素只是这样做:

<?php 
$array = array(
    "foo" => "bar", 
    42 => 24, 
    "multi" => array(
     "dimensional" => array(
      "array" => "foo" 
     ) 
    ) 
); 

/* Values are: 
* $array[42] --> outputs 24 
* $array['foo'] --> outputs bar 
* $array['multi']['dimensional']['array'] --> outputs foo 
*/ 
$sql = "INSERT INTO table (id, value1, value2) VALUES ($array[42], '$array['foo']', '$array['multi']['dimensional']['array']')"; 

?> 
+0

这样一个很好的评论家伙你的人摇滚感谢很多。你让人清醒 – user1210460

2

我同意乡亲的程度。确实要做出这样的事情是很困难的,但这不是不可能的。如果你收到的XML是标准的(相同数量的孩子等),并且xml非常简单,就像你的例子那么这是可能的。

此代码基于类似的东西,我做了一阵子回来。适用于此文件。尝试使用不同的XML并根据需要进行修改。(请记住,这是旧的代码和丑陋的种类,如果你愿意随意修饰它)

// create the database connection 
$con = mysql_connect("127.0.0.1","root","lolzapassword") or die('Could not connect: ' . mysql_error()); 

$xml_obj = simplexml_load_file('xml.xml'); 

// init some stuff 
$sql = array(); 
$fields = array(); 

// initial name is the table name 
$table_name = $xml_obj->getName(); 

// Create db if one doesn't exist (this is up to you. i use test) 
mysql_query('CREATE DATABASE IF NOT EXISTS test'); 

foreach($xml_obj->children() as $child) 
{ 
    $row = array(); 
    foreach($child->children() as $child) 
    { 
    $field = $child->getName(); // grab the name before we convert to string 

    $child = trim((string)$child); // converts from SimpleXMLElement and removes extra whitespace 
    if($child == '') 
     $child = -1; // make -1 if empty 

    $row[$field] = "'".mysql_real_escape_string($child, $con)."'"; // save the value hooray! 

    // fill the field creation array for table creation 
    if(!isset($fields[$field])) $fields[$field] = $field.' text'; 
    } 

    $sql[] = "INSERT INTO test.{$table_name} (".join(',', array_keys($row)).") values (".join(',',array_values($row)).")"; // store the row! 
} 

// create the table if it doesn't exist already. Since we have no idea what 
// format stuff comes in I make them text. If you want to be more specific you can 
// check types as best you can and make some assumptions from that. 
mysql_query('CREATE TABLE IF NOT EXISTS test.'.$table_name.' ('. join(',', $fields). ')'); 

// now we insert. remember, this code assumes that the xml is standard and there's 
// no extra nodes or children than expected. 
//print_r($sql); // if u want to see the sql commands 
foreach($sql as $insert){ 
    $result = mysql_query($insert, $con); 
    if(!$result) 
    exit("ZOMG ERROR! ".mysql_error($con)); 
}