r3wt
r3wt

Reputation: 4742

How to extract media:* namespace values in XML?

I need to extract three things from each item of an XML RSS feed from Zazzle's API.

Here is the feed: https://feed.zazzle.com/cityofhoops/rss

I need to get the title, price, thumbnail, and guid (link) from each item and add it to an array. I plan to encode this array to JSON so I can fetch it with AJAX and build the store view.

How can I do this? I've tried using foreach and reading the documentation but I'm failing to understand how I can get the values for each item, it seems not to work no matter what I try.

Here is the code I have so far:

$xml = simplexml_load_file('http://feed.zazzle.com/cityofhoops/rss');
echo '<pre>';
//echo json_encode($xml);
foreach($xml as $child){
    $new[] = [
              'img'=>(string)$child->attributes()->url,// ???
              'link'=>,
              'price'=>,
             ];
}
print_r($xml, false);

Upvotes: 1

Views: 547

Answers (1)

Kevin
Kevin

Reputation: 41885

You need to use ->children() method in and provide the namespace in order to get the values that you need. Example:

$data = array();
// add LIBXML_NOCDATA if you need those inside the character data
$xml = simplexml_load_file('http://feed.zazzle.com/cityofhoops/rss', 'SimpleXMLElement', LIBXML_NOCDATA);

foreach($xml->channel->item as $item) {
    $media = $item->children('media', 'http://search.yahoo.com/mrss/');

    $data[] = array(
        'title' => (string) $item->title,
        'price' => (string) $item->price,
        'guid' => (string) $item->guid,
        'link' => (string) $item->link,
        'author' => (string) $item->author,
        // 5.4 above dereference
        'thumbnail' => (string) $media->thumbnail->attributes()['url'],
        // if below, just assign $media->thumbnail->attributes() inside another variable first
        // then access it there
    );
}

echo '<pre>';
print_r($data);

Should output something like:

Array
(
    [0] => Array
        (
            [title] => City Of Hoops: Grind Mode Mugs
            [price] => $24.95
            [guid] => http://www.zazzle.com/city_of_hoops_grind_mode_mugs-168144869293766796
            [link] => http://www.zazzle.com/city_of_hoops_grind_mode_mugs-168144869293766796
            [author] => CityOfHoops
            [thumbnail] => http://rlv.zcache.com/city_of_hoops_grind_mode_mugs-rb83d2f2a678e4c5fa5287de6cc845a3a_x7jgp_8byvr_152.jpg
        )

Upvotes: 1

Related Questions