Posted: 2011-06-26
Category: How to's
That was a long title for this post o_o. Well , I first must clarify that my blog is not a wordpress mod, however it doesn’t mean I don’t have to work with wordpress at some point in the day. Recently I was doing a newsletter for a Website and I decided I would parse the RSS from that website to get the 4 newest contents however I ran into a trouble while using PHP’s SimpleXML class and this was that I SimpleXML couldn’t parse the contentn since it came with what is called namespace. For those of you who only came in here for the solution here it is =)
Replace <content:encoded> for <content> ;)
this is a simple example on how I did it
$data = file_get_contents(“http://myurls.com/feed.xml”);
$data = str_replace("content:encoded>","content>",$data);
$xml = simplexml_load_string($data);
$item = $xml->channel;
foreach($item->item AS $art)
{
$content = $art->content;
echo $content;
}
and thats it.
For those of you who kept reading I’m gonna tell you the solution to this problem, it’s indeed quite easy. Indeed a namespace tell us that what’s inside that tag is encoded in some other weird standard but don’t worry, the same feed it’s telling you what it is. if you see at the begining of the wordpress feed you’ll see this:
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
>
This is telling you that this uses these 3 namespaces: content,wfw and dc. So if you would like to get the job done properly you would have to parse your elements and their namespaces. this is how:
$data = file_get_contents('http://www.legrandjournal.com.mx/category/la-une/feed/');
$xml = simplexml_load_string($data);
$item = $xml->channel;
foreach($item->item AS $art)
{
//namespace for content
$ns_content = $art->childre('http://purl.org/rss/1.0/modules/content/');
//now simply use it
$contetnt = $ns_content->encoded;
echo $content;
}
It is exactly the same for dc and wfw namespaces =)
wow that was kinda easy wasn’t it ? Indeed those who left the site with my first solution are going to eventually have some problems if their wordpress feeds change or something, this way you stay cool and close to the standard.
Any suggestions, thoughts or whateva you’d like to say... Use the comments duh =P
Tweet
Comments
There are no comments

