reading an xml file in php and convert it into an associative array

Today, I will write about How to read an xml file from a source url/address and convert it into an array finally so that we can parse and use it. The code is so simple if you are using php 5.0 or higher. If you don't have php 5.0 or higher, this solution below is not for you. It has another solution which involves a few more lines of code.

Let's start with an url of a xml feed. Here is the link of BBC News Front page World Edition.

            http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml

This page shows the latest world news in an xml feed. Now, if you want to read that front page using a php script and use those news in your website, what you should do ?



I know, there may be lots of brilliant widgets to show the latest world news to a website, But i am just taking this as an example of how to parse that xml feed and I am considering you one of the future coder of those widgets.

Here is the code.
$SimpleXML_object = simplexml_load_file("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml");   
print_r($SimpleXML_object);
echo $SimpleXML_object->channel->title ;


The above code will output something like this. This was the output at the moment I was writing this.

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [version] => 2.0
        )

    [channel] => SimpleXMLElement Object
        (
            [title] => BBC News | News Front Page | World Edition
            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/default.stm
            [description] => Get the latest BBC World news: international news, features and analysis from Africa, Americas, South Asia, Asia-Pacific, Europe and the Middle East.
            [language] => en-gb
            [lastBuildDate] => Wed, 10 Mar 2010 01:18:42 GMT
            [copyright] => Copyright: (C) British Broadcasting Corporation, see http://news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse
            [docs] => http://www.bbc.co.uk/syndication/
            [ttl] => 15
            [image] => SimpleXMLElement Object
                (
                    [title] => BBC News
                    [url] => http://news.bbc.co.uk/nol/shared/img/bbc_news_120x60.gif
                    [link] => http://news.bbc.co.uk/go/rss/-/2/hi/default.stm
                )

            [item] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [title] => US attacks East Jerusalem plans
                            [description] => US Vice-President Joe Biden condemns Israel's approval of 1,600 new homes for ultra-Orthodox Jews in East Jerusalem.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/middle_east/8558850.stm
                            [guid] => http://news.bbc.co.uk/2/hi/middle_east/8558850.stm
                            [pubDate] => Tue, 09 Mar 2010 22:03:10 GMT
                            [category] => Middle East
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [title] => Dutch bishops order abuse inquiry
                            [description] => Dutch bishops order an inquiry into alleged sexual abuses of children by Catholic priests, threatening a new scandal.

                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/europe/8558311.stm
                            [guid] => http://news.bbc.co.uk/2/hi/europe/8558311.stm
                            [pubDate] => Tue, 09 Mar 2010 18:05:57 GMT
                            [category] => Europe
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [title] => US apology for Gaddafi comments
                            [description] => The US apologises for comments made after Libya's Col Gaddafi called for a holy war against Switzerland.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/africa/8558764.stm
                            [guid] => http://news.bbc.co.uk/2/hi/africa/8558764.stm
                            [pubDate] => Tue, 09 Mar 2010 20:24:35 GMT
                            [category] => Africa
                        )

                    [3] => SimpleXMLElement Object
                        (
                            [title] => N Ireland backs policing switch
                            [description] => Northern Ireland's assembly backs a key measure to devolve the highly sensitive issues of policing and justice from London.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/northern_ireland/8558466.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/northern_ireland/8558466.stm
                            [pubDate] => Tue, 09 Mar 2010 19:50:22 GMT
                            [category] => Northern Ireland
                        )

                    [4] => SimpleXMLElement Object
                        (
                            [title] => Ban honours UN's Haiti 'heroes'
                            [description] => Ban Ki-moon pays tribute to the 101 UN staff who died in the Haiti quake, as President Preval seeks US support on boosting the economy.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/americas/8558880.stm
                            [guid] => http://news.bbc.co.uk/2/hi/americas/8558880.stm
                            [pubDate] => Wed, 10 Mar 2010 00:12:44 GMT
                            [category] => Americas
                        )

                    [5] => SimpleXMLElement Object
                        (
                            [title] => Arrests in Cyprus body theft case
                            [description] => Three men are arrested in connection with the theft of the corpse of Cyprus's ex-President Papadopoulos, officials say.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/europe/8558979.stm
                            [guid] => http://news.bbc.co.uk/2/hi/europe/8558979.stm
                            [pubDate] => Wed, 10 Mar 2010 00:07:16 GMT
                            [category] => Europe
                        )

                    [6] => SimpleXMLElement Object
                        (
                            [title] => Nigeria 'ignored attack warnings'
                            [description] => A Nigerian governor accuses the army of ignoring warnings of attacks, as communal tension remains high near Jos.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/africa/8558246.stm
                            [guid] => http://news.bbc.co.uk/2/hi/africa/8558246.stm
                            [pubDate] => Tue, 09 Mar 2010 22:50:04 GMT
                            [category] => Africa
                        )

                    [7] => SimpleXMLElement Object
                        (
                            [title] => US woman on 'jihad terror' charge
                            [description] => A US woman from Pennsylvania faces charges of using the internet to recruit female militant fighters for deadly attacks abroad.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/americas/8558864.stm
                            [guid] => http://news.bbc.co.uk/2/hi/americas/8558864.stm
                            [pubDate] => Tue, 09 Mar 2010 23:56:49 GMT
                            [category] => Americas
                        )

                    [8] => SimpleXMLElement Object
                        (
                            [title] => Producer admits Letterman blackmail
                            [description] => A US TV producer pleads guilty to attempting to blackmail US chat show host David Letterman over his affairs.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/entertainment/8558781.stm
                            [guid] => http://news.bbc.co.uk/2/hi/entertainment/8558781.stm
                            [pubDate] => Tue, 09 Mar 2010 21:38:35 GMT
                            [category] => Entertainment
                        )

                    [9] => SimpleXMLElement Object
                        (
                            [title] => Good egg - DNA of extinct birds found in ancient shells
                            [description] => The eggshells of long-dead and extinct species are a particularly good source to find preserved DNA, researchers say.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/science/nature/8558683.stm
                            [guid] => http://news.bbc.co.uk/2/hi/science/nature/8558683.stm
                            [pubDate] => Wed, 10 Mar 2010 00:22:57 GMT
                            [category] => Science & Environment
                        )

                    [10] => SimpleXMLElement Object
                        (
                            [title] => UK gives condom aid ahead of World Cup 'festivities'
                            [description] => The UK donates £1m ($1.5m) to South Africa to buy 42m condoms, as the nation builds up to the football World Cup.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/africa/8557582.stm
                            [guid] => http://news.bbc.co.uk/2/hi/africa/8557582.stm
                            [pubDate] => Tue, 09 Mar 2010 16:21:57 GMT
                            [category] => Africa
                        )

                    [11] => SimpleXMLElement Object
                        (
                            [title] => Bendtner shines as Arsenal progress
                            [description] => Nicklas Bendtner silences his recent critics with a hat-trick as Arsenal see off Porto in emphatic fashion to reach the Champions League quarter-finals.
                            [link] => http://news.bbc.co.uk/go/rss/-/sport2/hi/football/europe/8555855.stm
                            [guid] => http://news.bbc.co.uk/sport2/hi/football/europe/8555855.stm
                            [pubDate] => Tue, 09 Mar 2010 21:41:03 GMT
                            [category] => Europe
                        )

                    [12] => SimpleXMLElement Object
                        (
                            [title] => Portsmouth 1-2 Birmingham
                            [description] => Two goals from Cameron Jerome inspire Birmingham to a battling win against bottom-club Portsmouth at Fratton Park.
                            [link] => http://news.bbc.co.uk/go/rss/-/sport2/hi/football/eng_prem/8549395.stm
                            [guid] => http://news.bbc.co.uk/sport2/hi/football/eng_prem/8549395.stm
                            [pubDate] => Tue, 09 Mar 2010 21:41:37 GMT
                            [category] => Premier League
                        )

                    [13] => SimpleXMLElement Object
                        (
                            [title] => Can US broker Middle East peace?
                            [description] => Joe Biden is in the region to encourage talks between the Palestinians and Israel. What can be achieved?
                            [link] => http://www.bbc.co.uk/go/rss/-/blogs/haveyoursay/2010/03/can_the_us_vicepresident_broke.html
                            [guid] => http://www.bbc.co.uk/blogs/haveyoursay/2010/03/can_the_us_vicepresident_broke.html
                            [pubDate] => Tue, 09 Mar 2010 12:24:35 GMT
                            [category] => Middle East
                        )

                    [14] => SimpleXMLElement Object
                        (
                            [title] => BBC World News
                            [description] => SimpleXMLElement Object
                                (
                                )

                            [link] => http://www.bbcworldnews.com/Pages/default.aspx
                            [guid] => http://www.bbcworldnews.com/Pages/default.aspx
                            [pubDate] => Tue, 29 Sep 2009 11:16:12 GMT
                            [category] => Programmes
                        )

                    [15] => SimpleXMLElement Object
                        (
                            [title] => Tracked down
                            [description] => Paedophile priest left untouched by Church and state
                            [link] => http://news.bbc.co.uk/go/rss/-/1/hi/programmes/newsnight/8556659.stm
                            [guid] => http://news.bbc.co.uk/1/hi/programmes/newsnight/8556659.stm
                            [pubDate] => Tue, 09 Mar 2010 13:32:53 GMT
                            [category] => Newsnight
                        )

                    [16] => SimpleXMLElement Object
                        (
                            [title] => Galapagos tension
                            [description] => Can all species live side by side in unique ecosystem? 
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/americas/8549901.stm
                            [guid] => http://news.bbc.co.uk/2/hi/americas/8549901.stm
                            [pubDate] => Wed, 10 Mar 2010 00:31:38 GMT
                            [category] => Americas
                        )

                    [17] => SimpleXMLElement Object
                        (
                            [title] => Biswas on India
                            [description] => Women's quotas - historic moment for largest democracy
                            [link] => http://www.bbc.co.uk/go/rss/-/blogs/thereporters/soutikbiswas/
                            [guid] => http://www.bbc.co.uk/blogs/thereporters/soutikbiswas/
                            [pubDate] => Tue, 09 Mar 2010 09:00:47 GMT
                            [category] => promo
                        )

                    [18] => SimpleXMLElement Object
                        (
                            [title] => Earth Watch
                            [description] => Whales and tuna tied up in Eurotangle
                            [link] => http://www.bbc.co.uk/go/rss/-/blogs/thereporters/richardblack/
                            [guid] => http://www.bbc.co.uk/blogs/thereporters/richardblack/
                            [pubDate] => Wed, 20 Jan 2010 10:36:28 GMT
                            [category] => UK Politics
                        )

                    [19] => SimpleXMLElement Object
                        (
                            [title] => Thin red line
                            [description] => Lone stand of anti-Taliban militia in Pakistan
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/south_asia/8537127.stm
                            [guid] => http://news.bbc.co.uk/2/hi/south_asia/8537127.stm
                            [pubDate] => Tue, 09 Mar 2010 13:08:02 GMT
                            [category] => South Asia
                        )

                    [20] => SimpleXMLElement Object
                        (
                            [title] => Separation fear
                            [description] => Families fight 'racist' Israeli marriage and citizenship law
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/middle_east/8552816.stm
                            [guid] => http://news.bbc.co.uk/2/hi/middle_east/8552816.stm
                            [pubDate] => Tue, 09 Mar 2010 09:05:16 GMT
                            [category] => Middle East
                        )

                    [21] => SimpleXMLElement Object
                        (
                            [title] => Obama backs Greece on speculators
                            [description] => President Barack Obama has 'responded positively' to calls to clamp down on market speculators, says the Greek PM after talks.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8558233.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8558233.stm
                            [pubDate] => Tue, 09 Mar 2010 21:27:13 GMT
                            [category] => Business
                        )

                    [22] => SimpleXMLElement Object
                        (
                            [title] => EU concern over end of tanker bid
                            [description] => Brussels says it hopes European aerospace group EADS was not prevented from fairly bidding for a major US defence deal.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8557769.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8557769.stm
                            [pubDate] => Tue, 09 Mar 2010 22:44:03 GMT
                            [category] => Business
                        )

                    [23] => SimpleXMLElement Object
                        (
                            [title] => Aer Lingus to make 670 job cuts
                            [description] => Aer Lingus announces plans to lay off 670 staff, including nearly a quarter of its cabin crew, as part of restructuring plans.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8558653.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8558653.stm
                            [pubDate] => Tue, 09 Mar 2010 18:47:28 GMT
                            [category] => Business
                        )

                    [24] => SimpleXMLElement Object
                        (
                            [title] => Hard drive evolution could hit XP
                            [description] => Hard drives are about to undergo one of the biggest format shifts in 30 years but it  could cause problems for Windows XP users.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/technology/8557144.stm
                            [guid] => http://news.bbc.co.uk/2/hi/technology/8557144.stm
                            [pubDate] => Tue, 09 Mar 2010 11:29:38 GMT
                            [category] => Technology
                        )

                    [25] => SimpleXMLElement Object
                        (
                            [title] => Porn net domain name plan revived
                            [description] => A plan to create a .xxx net domain for adult content will be revisited three years after it was rejected by internet regulators.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/technology/8556364.stm
                            [guid] => http://news.bbc.co.uk/2/hi/technology/8556364.stm
                            [pubDate] => Tue, 09 Mar 2010 11:51:07 GMT
                            [category] => Technology
                        )

                    [26] => SimpleXMLElement Object
                        (
                            [title] => Nanotech 'fuse' for novel battery
                            [description] => A never-before-seen reaction in nanotubes could make for batteries that pack a mighty punch, say researchers.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/science/nature/8556656.stm
                            [guid] => http://news.bbc.co.uk/2/hi/science/nature/8556656.stm
                            [pubDate] => Tue, 09 Mar 2010 17:17:28 GMT
                            [category] => Science & Environment
                        )

                    [27] => SimpleXMLElement Object
                        (
                            [title] => Pink Floyd take EMI to court
                            [description] => Pink Floyd launch legal action in the High Court against EMI over payment of online royalties and marketing of their music.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/entertainment/8558480.stm
                            [guid] => http://news.bbc.co.uk/2/hi/entertainment/8558480.stm
                            [pubDate] => Tue, 09 Mar 2010 17:31:30 GMT
                            [category] => Entertainment
                        )

                    [28] => SimpleXMLElement Object
                        (
                            [title] => Oscars 'most watched since 2005'
                            [description] => This year's Oscars ceremony in Los Angeles was the most watched in the US for five years, early figures suggest.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/entertainment/8557089.stm
                            [guid] => http://news.bbc.co.uk/2/hi/entertainment/8557089.stm
                            [pubDate] => Tue, 09 Mar 2010 11:10:05 GMT
                            [category] => Entertainment
                        )

                    [29] => SimpleXMLElement Object
                        (
                            [title] => LHC fault forces 2011 shutdown 
                            [description] => The Large Hadron Collider must be shut down for a year starting in late 2011 to address design flaws, the BBC has learned.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/science/nature/8556621.stm
                            [guid] => http://news.bbc.co.uk/2/hi/science/nature/8556621.stm
                            [pubDate] => Wed, 10 Mar 2010 00:19:18 GMT
                            [category] => Science & Environment
                        )

                    [30] => SimpleXMLElement Object
                        (
                            [title] => Third of EU emissions 'imported'
                            [description] => Research shows some EU countries "import" about a third of their carbon emissions from developing countries.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/science/nature/8557461.stm
                            [guid] => http://news.bbc.co.uk/2/hi/science/nature/8557461.stm
                            [pubDate] => Tue, 09 Mar 2010 12:46:03 GMT
                            [category] => Science & Environment
                        )

                    [31] => SimpleXMLElement Object
                        (
                            [title] => 'No proof' IVF aided by acupuncture
                            [description] => There is no evidence acupuncture or Chinese herbal medicine boost the chance of IVF success, fertility experts warn.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/health/8558527.stm
                            [guid] => http://news.bbc.co.uk/2/hi/health/8558527.stm
                            [pubDate] => Wed, 10 Mar 2010 00:17:10 GMT
                            [category] => Health
                        )

                    [32] => SimpleXMLElement Object
                        (
                            [title] => Somali hope for Chandlers release
                            [description] => Somali President Sharif Sheikh Ahmed says efforts are being made to release a UK couple held by pirates as soon as possible.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/england/kent/8557865.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/england/kent/8557865.stm
                            [pubDate] => Tue, 09 Mar 2010 17:14:19 GMT
                            [category] => Kent
                        )

                    [33] => SimpleXMLElement Object
                        (
                            [title] => Row over exhuming Rwanda leader
                            [description] => The son of Rwanda's first President, Dominique Mbonyumutwa, protests at orders to exhume his father's remains.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/africa/8557085.stm
                            [guid] => http://news.bbc.co.uk/2/hi/africa/8557085.stm
                            [pubDate] => Tue, 09 Mar 2010 15:25:11 GMT
                            [category] => Africa
                        )

                    [34] => SimpleXMLElement Object
                        (
                            [title] => Brazil slaps trade sanctions on US
                            [description] => Brazil is backed by the WTO as it slaps trade sanctions against US imports in retaliation for illegal subsidies to cotton farmers.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/americas/8556920.stm
                            [guid] => http://news.bbc.co.uk/2/hi/americas/8556920.stm
                            [pubDate] => Tue, 09 Mar 2010 08:31:50 GMT
                            [category] => Americas
                        )

                    [35] => SimpleXMLElement Object
                        (
                            [title] => Greece asks US for its assistance
                            [description] => Greece's prime minister asks the US to crack down on speculators he blames for worsening his country's debt woes.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8556944.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8556944.stm
                            [pubDate] => Tue, 09 Mar 2010 12:37:41 GMT
                            [category] => Business
                        )

                    [36] => SimpleXMLElement Object
                        (
                            [title] => Raids 'kill Indonesia militants'
                            [description] => Indonesian security forces kill three alleged militants and investigate whether one is key Bali bomb suspect Dulmatin.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/asia-pacific/8556964.stm
                            [guid] => http://news.bbc.co.uk/2/hi/asia-pacific/8556964.stm
                            [pubDate] => Tue, 09 Mar 2010 16:24:45 GMT
                            [category] => Asia-Pacific
                        )

                    [37] => SimpleXMLElement Object
                        (
                            [title] => Japan confirms secret nuclear pact
                            [description] => Japan confirms the existence of a secret Cold War pact allowing nuclear-armed US vessels to call at its ports. 
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/asia-pacific/8557346.stm
                            [guid] => http://news.bbc.co.uk/2/hi/asia-pacific/8557346.stm
                            [pubDate] => Tue, 09 Mar 2010 11:00:06 GMT
                            [category] => Asia-Pacific
                        )

                    [38] => SimpleXMLElement Object
                        (
                            [title] => Irish 'plot to kill cartoonist'
                            [description] => Seven people are arrested in the Irish Republic over an alleged plot to kill a Swedish cartoonist for depicting the Prophet Muhammad.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/europe/8558022.stm
                            [guid] => http://news.bbc.co.uk/2/hi/europe/8558022.stm
                            [pubDate] => Tue, 09 Mar 2010 18:24:33 GMT
                            [category] => Europe
                        )

                    [39] => SimpleXMLElement Object
                        (
                            [title] => Alcohol ban means Irish rugby fans face long Good Friday
                            [description] => Row as Irish crunch match Munster v Leinster is a mouth-watering clash for any rugby fan, but most drinkers in the Irish Republic wanting to toast the Magners League fixture in a bar next month will have to leave the country.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/europe/8557818.stm
                            [guid] => http://news.bbc.co.uk/2/hi/europe/8557818.stm
                            [pubDate] => Tue, 09 Mar 2010 16:57:16 GMT
                            [category] => Europe
                        )

                    [40] => SimpleXMLElement Object
                        (
                            [title] => Israeli 'spymaster' dies aged 82
                            [description] => A former Israeli spy who played a key role in Africa, the Middle East and the 1980s Iran-Contra scandal has died. 

                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/middle_east/8558332.stm
                            [guid] => http://news.bbc.co.uk/2/hi/middle_east/8558332.stm
                            [pubDate] => Tue, 09 Mar 2010 17:11:52 GMT
                            [category] => Middle East
                        )

                    [41] => SimpleXMLElement Object
                        (
                            [title] => Israel and Syria in nuclear bids
                            [description] => Israel and Syria both tell a conference in Paris they want to use nuclear power to generate electricity.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/middle_east/8558160.stm
                            [guid] => http://news.bbc.co.uk/2/hi/middle_east/8558160.stm
                            [pubDate] => Tue, 09 Mar 2010 16:01:25 GMT
                            [category] => Middle East
                        )

                    [42] => SimpleXMLElement Object
                        (
                            [title] => Indian MPs approve women's bill
                            [description] => India's upper house sees a second day of uproar as it backs a bill to reserve a third of all parliamentary seats for women.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/south_asia/8557237.stm
                            [guid] => http://news.bbc.co.uk/2/hi/south_asia/8557237.stm
                            [pubDate] => Tue, 09 Mar 2010 18:02:49 GMT
                            [category] => South Asia
                        )

                    [43] => SimpleXMLElement Object
                        (
                            [title] => UK seeks Afghan political drive
                            [description] => Foreign Secretary David Miliband is to urge the Afghan president to seek a political solution to the conflict with the Taliban.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/8559034.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/8559034.stm
                            [pubDate] => Wed, 10 Mar 2010 01:04:10 GMT
                            [category] => UK
                        )

                    [44] => SimpleXMLElement Object
                        (
                            [title] => US 'hid terror suspect treatment'
                            [description] => A former head of MI5 says she did not know US intelligence services were mistreating terror suspects until after she retired.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/8558958.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/8558958.stm
                            [pubDate] => Wed, 10 Mar 2010 00:01:57 GMT
                            [category] => UK
                        )

                    [45] => SimpleXMLElement Object
                        (
                            [title] => Baby P rules 'may increase risks'
                            [description] => Rules to improve child protection after the Baby P case may leave children more vulnerable to harm, council leaders warn.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/8558463.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/8558463.stm
                            [pubDate] => Wed, 10 Mar 2010 01:16:16 GMT
                            [category] => UK
                        )

                    [46] => SimpleXMLElement Object
                        (
                            [title] => Banking fraud 'moves to internet'
                            [description] => Fraudsters are continuing their switch from traditional card fraud to raiding online bank accounts, new research shows.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8558535.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8558535.stm
                            [pubDate] => Wed, 10 Mar 2010 00:00:44 GMT
                            [category] => Business
                        )

                    [47] => SimpleXMLElement Object
                        (
                            [title] => Social care deal 'dead in water'
                            [description] => Attempts to reach a cross-party deal on funding social care appear to be dead in the water ahead of a key summit.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/health/8557775.stm
                            [guid] => http://news.bbc.co.uk/2/hi/health/8557775.stm
                            [pubDate] => Wed, 10 Mar 2010 00:36:06 GMT
                            [category] => Health
                        )

                    [48] => SimpleXMLElement Object
                        (
                            [title] => MPs query coalfields revival plan
                            [description] => A £1bn government scheme to regenerate former coalmines has been poorly co-ordinated and lacks vision, MPs argue.
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/uk_news/politics/8558647.stm
                            [guid] => http://news.bbc.co.uk/2/hi/uk_news/politics/8558647.stm
                            [pubDate] => Wed, 10 Mar 2010 00:12:04 GMT
                            [category] => UK Politics
                        )

                    [49] => SimpleXMLElement Object
                        (
                            [title] => UK trade gap unexpectedly widens
                            [description] => The UK goods trade deficit with the rest of the world widens in January, causing the pound to dip below $1.50. 
                            [link] => http://news.bbc.co.uk/go/rss/-/2/hi/business/8557200.stm
                            [guid] => http://news.bbc.co.uk/2/hi/business/8557200.stm
                            [pubDate] => Tue, 09 Mar 2010 20:38:26 GMT
                            [category] => Business
                        )

                )

        )

)

This magic here, it is done by a single function simplexml_load_file() which is supported from php 5. This function converts the well-formed XML document in the given file to an SimpleXMLElement object.


This xml data in SimpleXMLElement Object, you can access these data as shown in the third line of the code,  $SimpleXML_object->channel->title  will give you the title of the feed. You have to use the schema of the xml to get the correct data.

Now, I want to convert this SimpleXMLElement Object into an associative array. Personally, I like to deal with associative arrays rather than this Object to avoid type casting and other things.

Usually, I use the following function to do this, I like this one because, it doesn't add the attributes and I don't need that. But if you need those attributes, you may check for some other functions here. Probably, I picked the following function from this page too.

function convertXmlObjToArr( $obj, &$arr )

    {
        $children = $obj->children();
        $executed = false;
        foreach ($children as $elementName => $node)
        {
            if( @array_key_exists( $elementName , $arr ) )
            {
                if(@array_key_exists( 0 ,$arr[$elementName] ) )
                {
                    $i = count($arr[$elementName]);
                    convertXmlObjToArr ($node, $arr[$elementName][$i]);    
                }
                else
                {
                    $tmp = $arr[$elementName];
                    $arr[$elementName] = array();
                    $arr[$elementName][0] = $tmp;
                    $i = count($arr[$elementName]);
                    convertXmlObjToArr($node, $arr[$elementName][$i]);
                }
            }
            else
            {
                $arr[$elementName] = array();
                convertXmlObjToArr($node, $arr[$elementName]);   
            }
            $executed = true;
        }
        if(!$executed&&$children->getName()=="")
        {    
            $arr = (String)$obj;
        }
        return ;
    }

Usage of this function : the full code will look like this


$SimpleXML_object = simplexml_load_file("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml");
$XMLDataAraay = array();
convertXmlObjToArr($SimpleXML_object, $XMLDataAraay);
print_r($XMLDataAraay);



And now, you will be able to access the title this way.   $XMLDataAraay['channel']['title'] 


Here, the last step of converting the Object into an Array may seem unnecessary. You can avoid this and deal directly with the object too.



And, Here is the new problem. If your site where you are going to use and extend this code to show data, this script will load the xml file every time from BBC's server. But every time, it is getting the same page unless this feed is updated in every minute.
2 problems are there I can remember of it for now, 
One, it is consuming your server's valuable bandwidth and another is the slower response of fetching the file first and then processing it.


Solution  : solution of this kind of problem is Caching. You can save a cache of the xml file with a suitable timeout and a timeout mechanism.. This system will save a copy of the xml file and every-time you request this file, this mechanism will look for the Cached file if the timeout interval (say, 15 minute, this means, we are expecting that this new feed will not be updated in next 15 minutes or, we can allow this maximum delay of getting that new news) of that cache file hasn't reached. If the cache file has timed out, it will refresh the cache file with new one and deliver it.

Sounds too much complex ? Actually, it is just a few lines of php code. I will discuss it some other day.  :)



1 comments :: reading an xml file in php and convert it into an associative array

  1. TEQTS Group was amazingly proficient and responsive and was energetic to learn new things to get the venture finished as per our quality norms. I will surely be employing them again for future ventures. Excellent work!! Your organization is tremendous

Post a Comment