-1

我正在尝试使用 PHP 和 YouTube 数据 API 将我所有的视频和视频信息放入 MySQL 数据库中。我正在使用该simplexml_load_file功能。我无法让它工作。它没有任何结果。(请原谅已弃用的 PHP/MySQL。)这是代码:

<?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>

4

1 回答 1

1

您忘记在循环中使用 $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;
}

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

于 2013-07-15T19:34:32.103 回答