PHP Simplexml - Namespace problem

Hi all

I have a small section of code working below, my problem is how do I output the elements with a namespace prefix?

Example:

<im:name>Blurred Lines</im:name>
<im:artist>Blackstreet</im:artist>

$rss = simplexml_load_file('https://itunes.apple.com/gb/rss/topsongs/limit%3D10/genre%3D15/explicit%3Dtrue/xml');

        echo '<h1>'. $rss->title . '</h1>';

        foreach ($rss->entry as $item) {
           echo '<h2>' . $item->title . '</h2>';
           echo '<p>' . $item->name . '</p>';
           echo '<p>' . $item->artist . '</p>';
           echo "<p>" . $item->price . "</p>";
           
        };

The <h1>, <h2> titles print ok, though the elements with im: just stay blank.
Is there a easy way to reference these?

Thanks, CB

Kevin Yank has a good article about this:

It looks like you need to grab all elements with a namespace using the children method.

Thanks Micky

I managed to find a solution quite similar which works great and we don’t have to hard-code the URL.

If anybodys interested:

foreach ($rss->entry as $item) {
           echo '<h2>' . $item->title . '</h2>';
           $namespaces = $item->getNameSpaces(true);
           $im = $item->children($namespaces['im']);
           echo '<p>' . $im->name . '</p>';
           echo '<p>' . $im->artist . '</p>';
           echo '<p>' . $im->price . '</p>';
        };

I’m now wondering how we could access the elements attributes.

In this instance, ''amount" and “currency” just as an example.

<im:price amount="0.99000" currency="GBP">£0.99</im:price>

I thought something like

echo '<p>' . $im->price->currency . '</p>';

Doesn’t work.

?

Thanks, CB

http://us1.php.net/manual/en/simplexmlelement.attributes.php

Reading the first user post by chris at chlab dot ch, I think you could probably do either of the following:


$im->price['currency'];
$im->price->{'currency'};

See how you get on.

Thanks.
I did fix this last night just didn’t want to bump up the thread :cool:

This seems to work.

$im->price->attributes()->currency

CB