Magnotta
Magnotta

Reputation: 941

read xml file attributes

i'm trying to read rss feed from url,i successfully got the title,description etc.
Now i'm facing problem while reading attributes info.
my xml is like this:

<item>
<guid>https://www.edx.org/node/22726</guid>
<title>Managing Projects with Microsoft Project</title>
<link>
 https://www.edx.org/course/managing-projects-microsoft-project-microsoft-cld213x
</link>
<description>
 Want to master project management? Have a project to manage but unsure where to begin? With over 20 million users, Microsoft Project is the go to app for project managers. 
</description>
<pubDate>Wed, 06 Jul 2016 16:21:40 -0400</pubDate>
<course:id>course-v1:Microsoft+CLD213x+2T2016</course:id>
<course:code>CLD213x</course:code>
<course:created>Thu, 16 Jun 2016 14:59:55 -0400</course:created>
<course:start>2016-07-11 00:00:00</course:start>
<course:end>2016-12-31 00:00:00</course:end>
<course:self_paced>0</course:self_paced>
<course:length>6 modules</course:length>
<course:prerequisites>
 Basic project management knowledge and skills Basic knowledge and skills using any current Windows® operating system (preferably Windows 10) Competency in using other Microsoft® Office® applications (preferably Office 2016)
</course:prerequisites>
</item> 

i can easily access title,description,pub date etc but facing problem while accessing <course:length> <course:id> <course:image-banner> etc

My php code is

<?php
 $rss = simplexml_load_file('https://www.example.org/api/v2/report/course-feed/rss');
echo '<h1>'. $rss->channel->title . '</h1>';
foreach ($rss->channel->item as $item) {
 echo '<h2><a href="'. $item->link .'">' . $item->title . "</a></h2>";
 echo "<p>" . $item->pubDate . "</p>";
 echo "<p>" . $item->description . "</p>";

} ?>

Upvotes: 0

Views: 48

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10460

This is a namespace problem! First, your document must have an xmlns:course="//URL" attribute. Then you can access your <course:*> like this:

$rss = simplexml_load_file('https://www.example.org/api/v2/report/course-feed/rss');
$namespaces = $rss->getNamespaces(true);//Add this line
echo '<h1>'. $rss->channel->title . '</h1>';
foreach ($rss->channel->item as $item) {
     echo '<h2><a href="'. $item->link .'">' . $item->title . "</a></h2>";
     echo "<p>" . $item->pubDate . "</p>";
     echo "<p>" . $item->description . "</p>";

     $course = $item->children($namespaces['course']);
     echo $course->id;
     echo $course->prerequisites;
}

Upvotes: 2

Related Questions