1

我正在处理 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";}
4

2 回答 2

3

更新:

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

它被称为 MySQL to XML - XML to 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 ;-) 

?>

如何插入值?

对重复的元素执行 a 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']')";

?>
于 2012-05-24T15:56:44.970 回答
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));
}
于 2012-05-24T16:23:04.620 回答