A small SimpleXML gotcha (with namespaces)

I've so far worked only very little with XML with namespaces, especially in terms of parsing it. Therefor, I was quite stumped today on the parsing of a particular snippet of XML which contained an element that had an xlink:href attribute. I just couldn't get that attribute's value out. The solution, as often seems to be the case, is quite simple.

It was my colleague Dynom who saved the day for me. He pointed me towards the second optional parameter of the attributes() method of the SimpleXMLElement object. Given the following snippet (within a larger snippet):

a text

I was using the first parameter of attributes (the namespace) to let SimpleXML know from which namespace I wanted to get the attributes:

$attributes = $xml->a->attributes('xlink' );
echo $attributes['href'];

This didn't work. $attributes['href'] didn't exist, and var_dump-ing the $attributes array returned an empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indicates if the attributes are actually prefixed by the namespace. As, in the above case, this is true, I have to set it to true (it defaults to false). So with this it worked:

$attributes = $xml->a->attributes('xlink', true);
echo $attributes['href'];

These are the kinds of details that you can get stumped on for ages, so I hope that people reading this will keep it in mind and remember it when they encounter a similar situation :)


Add comment

Comments

gravatar : what all those smilies?
June 4, 2008
gravatar left: good point, I removed the smiley from the code example. I hadn't noticed it for some reason.

I also noticed from your comment another bug ... the name isn't a requirement it seems :)
June 4, 2008
gravatar arne: Hey, thanks for the tip :)

It's saves me a lot of trying!
August 12, 2008
gravatar leon: Saved my week :)
June 12, 2009
gravatar James: Getting attributes to show with namespaces had me stumped for an hour. This article put me on the right track. Thanks so much!!!
June 26, 2009
gravatar Tails: Saved my day!
December 29, 2009
gravatar Kawika: Hey, thanks for this post. XML namespace parsing with SimpleXML has had me stumped for hours today, and this post helped a lot.
March 8, 2010
gravatar Round Sticker Printing: i agree with you.these parameter of attributes are good and help us.you discus a good topic int his post..thanks for sharing with us..
May 16, 2011
gravatar Tyler Morning Telegraph: you discus some good points in this post.
i like your post you do good effort to make it more valuable.
thanks for sharing.
May 27, 2011
gravatar secrets to weight loss: this work is so good and useful with a small Simple XML.i like to read informative blogs and this blog is also so good and helpful.thanks for taking time to discus this topic..
September 14, 2011
gravatar orlando screen room: I never looked at it like this before. I did not know that you could do this. I am glad to have this option.
October 28, 2011
gravatar fprsmag: Hey, thanks for this post. XML namespace parsing with SimpleXML has had me stumped for hours today, and this post helped a lot.

December 23, 2011
gravatar eros upcoming project: Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.

December 29, 2011
gravatar eros projects in gurgaon: I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

December 29, 2011
gravatar does nono work: I've been analyzing your own articles frequently. I have to declare that you are doing a amazing job. Remember to keep up the truly great writing.
January 17, 2012
gravatar Ansoo Lake: Interesting topic what you have shared with us. Your writing skill is really very appreciative. I love when you share your views through the best articles.Keep sharing and posting articles like these.This article has helped me a lot.Keep posting this stuff.

January 23, 2012
gravatar 5htp dosage withdrawal: empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indicates if the attributes are actually prefixed by the namespace. As, in the above case,
January 24, 2012
gravatar clarinet supplies buy: an empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indic
January 24, 2012
gravatar dimethylpentylamine dimethylamylamine: f details that you can get stumped on for ages, so I hope that people reading this will keep it in mind and remember it when they encounter a similar situati
January 24, 2012
gravatar shizandrol a drug test: f'] didn't exist, and var_dump-ing the $attributes array returned an empty array. However, clearly I should learn to read better, because the manual does mention the second parameter $is_prefix, which is a boolean that indicates if the attributes are actually prefixed by the namespace. As, in the above case, this is true
January 24, 2012
gravatar yohimbine hydrochloride usp: first parameter of attributes (the namespace) to let SimpleXML know from which namespace I wanted to get the attributes:
January 24, 2012
gravatar furniture stores phoenix:
Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb.
Please keep them coming. Greets!!!
January 26, 2012
gravatar coach outlet online: If you buy Coach items at the
coach outlet online

store, the goods will be sent out within 24 hours after confirming your payment and arrive to your door within 7 work days.No one can deny the shopping at the
coach factory outlet

is satisfactory. For the low prices and good quality.
January 29, 2012
gravatar coach outlet: coach outlet

handbags You can not just save your cash but also your time inside a convenient way to obtain the exact same bags product and do not be concerned the shippment of one's products.The
coach outlet store online

are utilized for formal event in company area that will display your excellent taste.Not only does a briefcase make is easier to carry things.
January 29, 2012
gravatar modern furniture phoenix az: I am sure my visitors will locate that extremely useful.
January 30, 2012
gravatar como reducir el colesterol: Great job man :D 8O 8O
February 1, 2012
gravatar discount uggs boots: Your first-class knowledge about this good post can become a proper basis for such people. nice one! :evil:
February 1, 2012
gravatar michael kors outlet: Thank you for this great resource, these articles are very helpful (so many left to read). Awesome job and thanks again for doing something for other people on your day.

February 1, 2012
gravatar Pillows: I think this is a nice place. Thanks for taking the time to post such an informative article. It has given me a lot of inspiration.

February 2, 2012
gravatar game of thrones: thx code works like a charm :lol:
February 3, 2012

Php5_zce_logo

Upcoming events

I will be speaking 06-02-2012: D-Day
I will be speaking 17-02-2012: Techademy Trainingday February
I will be speaking 23-02-2012: Zend Webinar: Git for Subversion Users

Tags

1337 2008 2010 2011 4developers access modifiers accessibility AdaLovelaceDay09 advent agavi agile alfred amsterdam apache api apple article articles atk atkMetaNode audioscrobbler automation azure backwards compatibility barcelona barcodes bash bbc bbq beatstad belgium best practices bittorrent blogging blogs boards of canada book books bughuntday bundle caching cake cal evans calendar career cat cerf certificate cfp clear cms cologne common sense communities community components conference conferences contest continuous integration contribute contribution crisis css custom d-day datetime DbFinderPlugin decorator decorators deployment devdays development directoryindex docblox doctrine documentation download dpc dpc09 dpc10 dpc11 DPC2008 dreamhost drupal dv7 eclipse ed editors efficiency enterprise errors event events expertise ezcomponents facebook finland flickr fork framework frameworks freelance freeze frontend fun game games geoip germany getting real git github gnome-do google google calendar googletalk graceful degradation hack hackers hidden gem hiphop howto hp HR html http i386 ibuildings icann ide ideasofmarch idm imovie indy ingewikkeld integration international php conference internet interview ipad IPC ipc ipc08 ipc10 ipc11se iterm2 javascript jenkins jenkins-php job job openings jobeet john peel joomla joomladays kiva kubuntu launcher launchy left on the web libraries library lighttpd lime linktuesday linux live london loudblog m2ts mac magazines malware mambo marjolein mediterra meeting meme meta methodology micro-financing microframework microsoft migration movie music mysql namespace namespaces netbeans netherlands newsfire nllgg nos odmarco open source opinion ORM osx paradiso paris partnership pavilion pear pecl performance personal pfc10 pfc11 pfcongres pfcongrez pfz photo php php5.3 phpabstract phpazure phpBB phpbb phpbelgium phpbenelux phpbnl10 phpday phpdoc phpdocumentor phpgg phpitalia phpnw phpnw08 phpnw11 phpstorm phptek phptek09 phpuk2009 phpUnderControl phpunit php|architect php|tek podcast politics portability postcrossing presentation presentations private projects protected prototype PSR-0 public python qa qr codes re2c recruiting refactoring review rewrite ruby on rails san francisco schedule scifi script security sensio seven things sfdaycgn sflive2011 shell scripting silex simplexml slides smfony software sogeti solar sound speakers spl ssh standard standards star trek static steer strings stylesheets subversion symfony symfony live Symfony2 symfonycamp symfonyday symfonylive symfonyUnderControlPlugin talk talks techademy technology techportal tek09 telecommuting terratec terrorism testfest testing textmate textpattern the right tool timeout tips tld todo tomas tools training twig uncon unet usability usergroup validation vhost video vim vinyl virus warp webinar weblogging webservices wiki windows winphp women wordpress work workshop world world of warcraft wpi writing wunderlist xml xpath xsd yara year youtube zc11 ZCE zemanta zend zend framework zend server zend studio zendcon Zend_Form zite
© 2004 - 2012 Stefan Koopmanschap + Powered by Symfony, photos powered by Flickr, links powered by Delicious, Shanghai smilies by Iconbuffet. Feeds: rss / atom. Left on the Web v4.4.0.1