数据库的XML提要


XML Feed to Database

我正在尝试使用PHP和YouTube Data API将我所有的视频和视频信息放入MySQL数据库中。我正在使用simplexml_load_file函数。我不能让它工作。它没有产生任何结果。(原谅不推荐使用的PHP/MMySQL。)这是代码:

<?php
mysql_connect('localhost', '*NOT NEEDED*', '*NOT NEEDED*');
mysql_select_db('demoScript');
mysql_query("TRUNCATE videos");
$url = "http://gdata.youtube.com/feeds/api/users/demoScript/uploads";
$xml = simplexml_load_file($url);
$targeti = substr_count($url, "<entry>");
for($i=0; $i<$targeti; $i++){
    $title = $xml->entry->title;
    $id = $xml->entry->id;
    $date = $xml->entry->published;
    $views = $xml->entry->yt['viewCount'];
    $rating = $xml->entry->gd['average'];
    $faves = $xml->entry->yt['favoriteCount'];
    $desc = $xml->entry->content;
    mysql_query("INSERT INTO `videos` VALUES ('".$id."','".$title."','".$date."','".$views."','".$rating."','".$faves."','".$desc."')");
}
?>
<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='css/bootstrap.css' />
    <link rel='stylesheet' href='css/bootstrap-responsive.css' />
</head>
<body>
    <ul class='nav nav-tabs'>
        <div class='brand' style='float: right; margin-right: 10px; margin-top: 8px; font-size: 20px;'>demoScript</div>
        <li class='active'><a href='#'>Home</a></li>
        <li><a href='#'>About</a></li>
        <li><a href='#'>Videos</a></li>
        <li><a href='#'>Contact</a></li>        
    </ul>
    <div class='hero-unit'>
        <center><h2>Most Viewed Video</h2></center><p />
    </div>
    <script src='js/bootstrap.js'></script>
</body>

您忘记在循环中使用$i。您可以执行类似$xml->entry[$i];的操作,但是simplexml_load_file已经为您提供了一个对象。你可以用循环它的子代

foreach($xml->nameOfParentTag as $entry){
   $title = $entry->title;
   $id = $entry->id;
   $date = $entry->published;
   $views = $entry->yt['viewCount'];
   $rating = $entry->gd['average'];
   $faves = $entry->yt['favoriteCount'];
   $desc = $entry->content;
}

而不是使用子字符串计数器。