Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading itunes XML file with PHP DOM method

I'm having some trouble in getting information from my itunes XML feed which you can peek at here: http://c3carlingford.org.au/podcast/C3CiTunesFeed.xml

I need to get the information from each of the inner <item> tags. An example of one of these is as follows:

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

Now i have had some success! I have been able to get the title out of it all:

<?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 />';
    };

?>

But I can't seem to get anything else out... I'm new to all this!


So What I need to get out includes:

  1. The <itunes:author> value.
  2. The url attribute value from the <enclosure> tag

Would someone help me getting these two values out?

like image 203
Ben Potter Avatar asked Jul 03 '26 23:07

Ben Potter


1 Answers

You can use DOMXPath to do this and make your life a lot easier:

$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";
}

You can see from the demo that this will output:

What to do when a viper bites you - Ps. Phil Buechler - http://www.ccccarlingford.org.au/podcast/C3C-20120722PM.mp3
like image 198
nickb Avatar answered Jul 06 '26 13:07

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!