从XML feed将数据插入MySQL数据库

时间:2014-01-14 14:56:18

标签: php mysql xml

有人帮我用这个脚本将XML数据插入MySQL,XML数据来自audioscrobbler.com API,我需要用xml数据 $ song_album <将一行插入mysql数据库/ strong>, $ song_albumURL $ song_tag ,但即使我在数据库中获取数据,我也会添加12次相同的歌曲数据,数据为在不同的行。我可以帮助解决这个问题吗?

<?php
error_reporting(E_ALL);
$mysql_hostname = "localhost";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "database";
$myAPIKey = '****';

// Connect
$mysqli = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);

if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$artist_raw = 'Metallica';
$title_raw = 'Whiskey In The Jar';
$artist = urlencode($artist_raw);
$title = urlencode($title_raw);

$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=$myAPIKey&artist=$artist&track=$title") 

   or die("Error: Cannot create object");


foreach($xml->track->children() as $track => $data){
$song_album = $data->title;
$song_tag = $data->tag->name[0];
$song_albumURL = $data->image[2];

$xml = NULL;
$stmt = $mysqli->prepare("INSERT INTO `music` (`song_title`, `song_artist`, `song_album`, `song_tag`, `song_albumURL`) values ('{$title_raw}', '{$artist_raw}', '{$song_album}', '{$song_tag}', '{$song_albumURL}')");
$stmt->bind_param('s', $song_album, $song_albumURL, $song_tag);
$stmt->execute();
$stmt->close();

}
?>

这是XML原始数据:

<lfm status="ok">
<track>
<id>1003737</id>
<name>Whiskey in the Jar</name>
<mbid>664ae92a-f25a-4df4-a564-66ee87dff1c8</mbid>
<url>...</url>
<duration>303000</duration>
<streamable fulltrack="0">0</streamable>
<listeners>433263</listeners>
<playcount>3389216</playcount>
<artist>
<name>Metallica</name>
<mbid>65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab</mbid>
<url>http://www.last.fm/music/Metallica</url>
</artist>
<album position="9">
<artist>Metallica</artist>
<title>Garage, Inc.</title>
<mbid/>
<url>http://www.last.fm/music/Metallica/Garage,+Inc.</url>
<image size="small">http://userserve-ak.last.fm/serve/64s/54059755.png</image>
<image size="medium">http://userserve-ak.last.fm/serve/126/54059755.png</image>
<image size="large">http://userserve-ak.last.fm/serve/174s/54059755.png</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/300x300/54059755.png
</image>
</album>
<toptags>
<tag>
<name>metal</name>
<url>http://www.last.fm/tag/metal</url>
</tag>
<tag>
<name>heavy metal</name>
<url>http://www.last.fm/tag/heavy%20metal</url>
</tag>
<tag>
<name>hard rock</name>
<url>http://www.last.fm/tag/hard%20rock</url>
</tag>
<tag>
<name>rock</name>
<url>http://www.last.fm/tag/rock</url>
</tag>
<tag>
<name>cover</name>
<url>http://www.last.fm/tag/cover</url>
</tag>
</toptags>
<wiki>...</wiki>
</track>
</lfm>

1 个答案:

答案 0 :(得分:1)

您的foreach遍历<track>节点的子节点,并在每次迭代时插入(不完整的)行(对于每个子节点,即)。

这不是你想要的。您想在此处插入一行。删除循环并执行以下操作:

$song_album = $xml->track->album->title;
$song_tag = $xml->track->toptags->tag[0]->name;
dbQuery('INSERT INTO ...');