从XML捕获数据并保存在数据库中

时间:2012-05-24 14:59:57

标签: php mysql xml

我正在处理XML文件,我需要通过PHP读取,然后将该数据保存在数据库中。到目前为止我成功了。问题是,它是专门为下面的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";}

2 个答案:

答案 0 :(得分:3)

<强>更新

在互联网上搜索,我发现这个课可能对你有帮助:

它被称为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


第一个想法:

有人在你的问题评论中说:

“数据库具有预定义的结构 - 表,列,字段类型等,因此导入”任何“类型的XML意味着您将需要构建一些可以构建动态数据库结构,以便您的PHP脚本可以正确地将数据插入该数据库中的正确位置“

他是对的,这几乎是不可能的。我的建议是使用一个类来解析XML。这个类将XML转换为$array,这样你就可以获得mysql insert所需的任何元素(我认为这是你能做的最好的)。

在此处下载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']')";

?>

答案 1 :(得分: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));
}