从 xml 文件创建 html5 播放列表


Create a html5 playlist from an xml file

我正在尝试使用audiojs插件创建一个HTML5播放列表。我的播放列表位于外部 XML 文件中,因为它由自定义 CMS 管理:

<playlist>
   <item>
     <title>bla bla bla</title>
     <artist>Big Bla</artist>
     <path>/mp3/bla-bla-bla.mp3</path>
   </item>
   <item>
     <title>bla bla blab</title>
     <artist>lil Big Bla</artist>
     <path>/mp3/bla-bla-bla.mp3</path>
   </item>
</playlist>

这是我.php文件:

        <div id="player-holder">
            <audio preload></audio>
            <ul>
                <li>
                    <a data-src="track path" href="#">title</a>
                </li>
                <li>
                    <a data-src="track path" href="#">title</a>
                </li>
                <li>
                    <a data-src="track path" href="#">title</a>
                </li>
            </ul>
        </div>

我需要从 XML 文档中获取歌曲路径并将其添加到"data-src"属性中,并获取歌曲标题并将其显示为锚链接。

我有大约 6 首曲目进入播放列表,因此我需要遍历 XML 中的每个项目并将该数据输出到其自己的列表项中。

PHP 有一个内置的 XML 解析器。

http://php.net/manual/en/book.xml.php

编辑:如果你的结构提前知道,这个库可能会更容易工作......http://www.php.net/manual/en/simplexml.examples-basic.php

使用它以及 CURL 或标准file_get_contents()调用,您应该能够让服务器检索 XML,将其解析为树结构,并循环访问结果以生成用于显示的 HTML。

<?php
$playlistXML = file_get_contents('http://whatever.cms.com/playlist.xml');
$playlist = new SimpleXMLElement($playlistXML);
foreach($playlist->item as $song) {  ?>
   <a href="<?= $song->path; ?>"><?= $song->title.' - '.$song->artist; ?> </a>
<?php } ?>

我会投票给SimpleXML。

总而言之,您将从服务器加载 XML,使用 SimpleXML 对其进行解析,然后迭代列表中的每首歌曲,以使用提供的标题和艺术家模板列表项。

<?php
/* first load the XML and create the containing div */
    $playlistRawXML = file_get_contents('http://example.com/path/to/playlist.xml');
    try {
       $playlist = new SimpleXMLElement($playlistRawXML);
    } catch (Exception $e) {
       /* if SimpleXML can't parse the file, it'll throw an exception */
       echo "XML parsing error";
       var_dump($e);
       exit;
    }
?>
<div id="player-holder">
    <audio preload></audio>
    <ul>
<?php
    /* then, for each song in the playlist, render a list item: */
    foreach($playlist->item as $song) {  
        echo '<li><a data-src="' . $song->path . '" href="#">' . $song->title . ' (' . $song->artist . ')</a></li>';
     }
     /* and then end the list, div, etc.: */
 ?>
  </ul>
</div>