使用PHP DOM方法读取itunes XML文件

Ben*_*ter 0 php xml parsing itunes xml-parsing

我从itunes XML feed获取信息时遇到了一些麻烦,你可以在这里查看:http://c3carlingford.org.au/podcast/C3CiTunesFeed.xml

我需要从每个内部<item>标签获取信息.其中一个例子如下:

<item>
    <title>What to do when a viper bites you</title>
    <itunes:subtitle/>
    <itunes:summary/>
    <!-- 4000 Characters Max ******** -->
    <itunes:author>Ps. Phil Buechler</itunes:author>
    <itunes:image href="http://www.c3carlingford.org.au/podcast/itunes_cover_art.jpg"/>
    <enclosure url="http://www.ccccarlingford.org.au/podcast/C3C-20120722PM.mp3" length="14158931" type="audio/mpeg"/>
    <guid isPermaLink="false">61bc701c-b374-40ea-bc36-6c1cdaae8042</guid>
    <pubDate>Sun, 22 Jul 2012 19:30:00 +1100</pubDate>
    <itunes:duration>40:01</itunes:duration>
    <itunes:keywords>
        Worship, Reach, Build, Holy Spirit, Worship, C3 Carlingford
    </itunes:keywords>
</item>
Run Code Online (Sandbox Code Playgroud)

现在我取得了一些成功! 我已经能够获得所有标题:

<?php 
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->load('http://c3carlingford.org.au/podcast/C3CiTunesFeed.xml');
    $items = $dom->getElementsByTagName('item');

    foreach($items as $item){                       
        $title = $item->getElementsByTagName('title')->item(0)->nodeValue;
            echo $title . '<br />';
    };

?>
Run Code Online (Sandbox Code Playgroud)

但我似乎无法得到任何其他东西......我对这一切都是新手!


所以我需要了解的内容包括:

  1. <itunes:author>值.
  2. <enclosure>标记的url属性值

有人会帮助我获得这两个价值吗?

nic*_*ckb 5

您可以使用DOMXPath这样做,让您的生活更轻松:

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML( $xml); // $xml = file_get_contents( "http://www.c3carlingford.org.au/podcast/C3CiTunesFeed.xml")

// Initialize XPath    
$xpath = new DOMXpath( $doc);
// Register the itunes namespace
$xpath->registerNamespace( 'itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd');

$items = $doc->getElementsByTagName('item');    
foreach( $items as $item) {
    $title = $xpath->query( 'title', $item)->item(0)->nodeValue;
    $author = $xpath->query( 'itunes:author', $item)->item(0)->nodeValue;
    $enclosure = $xpath->query( 'enclosure', $item)->item(0);
    $url = $enclosure->attributes->getNamedItem('url')->value;

    echo "$title - $author - $url\n";
}
Run Code Online (Sandbox Code Playgroud)

您可以从演示中看到这将输出:

What to do when a viper bites you - Ps. Phil Buechler - http://www.ccccarlingford.org.au/podcast/C3C-20120722PM.mp3
Run Code Online (Sandbox Code Playgroud)