0

I wrote code that get data from http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml

  for($i = 0; $i < 10; $i++){

   $title = $xml->entry[$i]->title;  // work
   $name = $xml->entry[$i]->im:name;  //does not work

   $html .= "<br />$title<hr />";} echo $html;

The problem is im .I cannot get data of it . How can I solve it ?

Mohammed
  • 51
  • 1
  • 8

1 Answers1

0

You can not access <im:name> in that way.

im: is a NameSpace prefix: to work with namespaced tags you have to use a specific syntax.

You can retrieve all document’s Namespaces URI using:

$namespaces = $xml->getDocNamespaces();

and you will obtain this array:

Array
(
    [im] => http://itunes.apple.com/rss
    [] => http://www.w3.org/2005/Atom
)

Each array key is the Namespace prefix, each array value is the Namespace URI. The URI with an empty key represents global document Namespace URI.

SimpleXML has not the best syntax to work with Namespaces (IMO DOMDocument is a better choice). In your case, you have to do in this way:

$children = $xml->entry[$i]->children( 'im', True );
echo $children->artist . '<br>';
echo $children->name . '<br>';

Result for ->entry[0]:

Prince & The Revolution
Purple Rain

The ->children second parameter True means “regard first parameter as prefix”; as alternative, you can use complete Namespace URI in this way:

$children = $xml->entry[$i]->children( 'http://itunes.apple.com/rss' );

                                  ... ♪ I only wanted to see you laughing in the purple rain ♪ ...

fusion3k
  • 11,568
  • 4
  • 25
  • 47