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; 
}
5
  • 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. Commented Oct 17, 2012 at 6:15
  • @jheddings : Just tried that. The loop is not being entered only Commented Oct 17, 2012 at 6:21
  • @jheddings is correct, see codepad.viper-7.com/J4cn9r Commented Oct 17, 2012 at 6:22
  • @Phil : It's not working for me. Tried the following : return (string) $item->content['url']; Commented Oct 17, 2012 at 6:30
  • @jheddings: That only works because the fragmentary XML doesn't include the namespace declaration. If you use <item xmlns:media="http://example.com"> it will stop working. Commented Oct 17, 2012 at 13:53

2 Answers 2

1

Use xPath() method of the SimpleXMLElement()

var_export($item->xpath('media:content'));
Sign up to request clarification or add additional context in comments.

1 Comment

Why does everyone think you need XPath to use namespaces in SimpleXML? You absolutely do not.
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; 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.