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 クラス「Clean XML to array」をここからダウンロードします。

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 ;-) 

?>

値を挿入する方法は?

繰り返される要素に対してafor 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 に答える