$rss = simplexml_load_file('URL');
foreach ($rss->channel->item as $item) {
$title = strip_tags($item->title);
$desc = strip_tags($item->description);
}
MY XML DATA LIKE:
<title> <![CDATA[ Title data here ]]></title>
<description><![CDATA[ Description here ]]> </description>
<media:group>
<media:content url="https://myurl.com/poster.jpg?width=1920" medium="image" type="image/jpeg"/>
<media:content url="https://myurl.com/videos/erer-sdfer.mp4" duration="100" width="320" height="180" fileSize="4234581"
</media:group>
In the XML above I can retrieve the title and description information, but I need to have access to the "url" property value from the media:group -> media:content node. Please assist me in locating this.
These elements use a different namespace. Look for the xmlns:media
namespace definition in your XML document. The value is the actual namespace. It should be http://search.yahoo.com/mrss/
in this case - Media RSS.
SimpleXML uses the default namespace of the current element until you select another. The SimpleXMLElement::children()
and SimpleXMLElement::attributes()
methods have an argument for the namespace.
// define a dictionary for the used namespaces
$xmlns = [
'mrss' => 'http://search.yahoo.com/mrss/'
];
$rss = simplexml_load_string(getXMLString());
foreach ($rss->channel->item as $item) {
$title = strip_tags($item->title);
$description = strip_tags($item->description);
var_dump($title, $description);
// fetch elements of the specified namespace
foreach ($item->children($xmlns['mrss'])->group->content as $content) {
var_dump((string)$content->attributes()->url);
}
}
function getXMLString() {
return <<<'XML'
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<item>
<title> <![CDATA[ Title data here ]]></title>
<description><![CDATA[ Description here ]]> </description>
<media:group>
<media:content url="https://myurl.com/poster.jpg?width=1920" medium="image" type="image/jpeg"/>
<media:content url="https://myurl.com/videos/erer-sdfer.mp4" duration="100" width="320" height="180" fileSize="4234581"/>
</media:group>
</item>
</channel>
</rss>
XML;
}
Output:
string(18) " Title data here "
string(19) " Description here "
string(39) "https://myurl.com/poster.jpg?width=1920"
string(39) "https://myurl.com/videos/erer-sdfer.mp4"