Search code examples
phprsssimplexmlxml-namespaces

Getting media url attribute from SimpleXMLElement object


I want to get 'url' attribute from 'media:content' tag of a RSS using simplexml. I searched the net for hours but cannot get it to work. This is the code:

<?php
$rss ='<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
    <channel>
        <item>
            <media:content url="http://blog.com/image1.jpg" width="661" height="310"/>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($rss);
$url = $xml->children('media', true)->content;

var_dump($xml);
var_dump($url); // <- This is object(SimpleXMLElement)[3]
var_dump($url['url']); // <- This is NULL

The $url is NULL. ->content returns a SimpleXMLElement but it hasn't any url attribute!


Solution

  • You could use SimpleXMLElement xpath with for example this expression to get the media:content element:

    /rss/channel/item/media:content

    $xml = simplexml_load_string($rss);
    $urls = $xml->xpath('/rss/channel/item/media:content');
    
    // Get url from the first match
    echo $urls[0]->attributes()->url;
    
    // Loop all the matches
    foreach ($urls as $url) {
        echo $url->attributes()->url;
    }
    

    Php demo output

    Or you can loop though the children for this item:

    foreach ($xml->channel->item->children("media", true) as $child) {
        echo $child->attributes()->url;
    }
    

    Php demo output