问题在我的XML数组到mySQL脚本,我不能导入多个节点


Problem in the array of my XML to mySQL script, I can not import more than one node

我正试图将我的XML导入mySQL。但是,我现在只添加了第一个(如下面的XML)。我想要的是在XML和其他文件中添加根元素。我不介意代码是否本地化到我使用的确切字段。

表的名称是xml2msql,字段是to、from、heading、body

如果你有你自己的代码,那将是伟大的,如果你与我分享。

下面的代码是全球化的,如果你的xml元素和mysql字段是相同的,在相同的顺序。

$columns = array();
$data = array();
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  $columns[] = $child->getName();
  $data[] = (string)$child;
  }
$col = '`'. implode('`,`',$columns) .'`';
$val = "'". implode("','",$data)."'";
$query = "INSERT INTO xml2mysql ($col) VALUES ($val)";
echo $query;
mysql_query($query);

这是与上面的代码一起工作的XML

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>

,这是最好的xml

<notes>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>
<note>
<to>Mary</to>
<from>Nick</from>
<heading>Letter</heading>
<body>Reminder about your dog</body>
</note>
<notes>

您需要像这样遍历每个注释:

foreach($xml->note as $note)
{
    $columns = array();
    $data = array();
    foreach($note->children() as $child)
    {
        echo $child->getName() . ": " . $child . "<br />";
        $columns[] = $child->getName();
        $data[] = (string)$child;
    }
    $col = '`'. implode('`,`',$columns) .'`';
    $val = "'". implode("','",$data)."'";
    $query = "INSERT INTO xml2mysql ($col) VALUES ($val)";
    echo $query;
}

我用您提供的XML试过了,它成功了。