0

Possible Duplicate:
PHP namespace simplexml problems

I have a portion of xml as :

<item>
    <source url="eurosport.com">Eurosport</source>
    <media:content url="http://media.zenfs.com/en_GB/Sports/Eurosport/900589-15042881-640-360.jpg" type="image/jpeg" width="130" height="86" />
</item>

I am using the SimpleXMLElement() to convert the textual xml data into a SimpleXML Element Object. By that I can has access to item as $item.

I am required to obtain the url of media:content and am not able to do it. Can anyone help me out?

P.S: Tried this, but it did not help ..

foreach ($item->{'media:content'}->attributes() as $key => $val) {
        return (string)$val; 
}
Community
  • 1
  • 1
S..K
  • 1,944
  • 2
  • 14
  • 16
  • 1
    Have you tried simply `$item->{'content'}`? Many simple parsers only require the node name... You can use the prefix or NS if you like, but it is not often required. – jheddings Oct 17 '12 at 06:15
  • @jheddings : Just tried that. The loop is not being entered only – S..K Oct 17 '12 at 06:21
  • @jheddings is correct, see http://codepad.viper-7.com/J4cn9r – Phil Oct 17 '12 at 06:22
  • @Phil : It's not working for me. Tried the following : return (string) $item->content['url']; – S..K Oct 17 '12 at 06:30
  • @jheddings: That only works because the fragmentary XML doesn't include the namespace declaration. If you use `` it will stop working. – IMSoP Oct 17 '12 at 13:53

2 Answers2

1

Use xPath() method of the SimpleXMLElement()

var_export($item->xpath('media:content'));
Udan
  • 5,429
  • 2
  • 28
  • 34
  • 1
    Why does everyone think you need XPath to use namespaces in SimpleXML? You absolutely do not. – IMSoP Oct 17 '12 at 13:49
1

You need to use the ->children() method to select the correct namespace:

foreach ($item->children('media', true)->content->attributes() as $key => $val) {
        return (string)$val; 
}
IMSoP
  • 89,526
  • 13
  • 117
  • 169