开发者

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

I am trying to import my XML to mySQL. However what I have now, adds only the first (as the XML below). What I want and is not working, is to add a root element in the XML and other . I don't mind if the code is localized to the exact fields I use.

The name of the table is xml2msql and the fields are to, from, heading, body.

If you have your very own code that will work, that would be great if you share it with me.

The code below is kind of globalized if your xml elements and mysql fields are the same and in the same order.

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

this is the xml that works with the code above

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

and this is the preferable 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&g开发者_如何学Pythont;
<body>Reminder about your dog</body>
</note>
<notes>


You need to iterate through each note like this:

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

I tried this with the XML you provided and it does the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜