-1

I am wondering how I can parse this xml feed with php?

http://www.shinyloot.com/feeds/games_on_sale

I know I can use this to start with:

$shinyloot = simplexml_load_file('http://www.shinyloot.com/feeds/games_on_sale');

From there I am unsure as the best way to parse it is it's a more complicated one with multiple arrays inside.

Also this is not a duplicate it's a specific case and the answers you lot linked are not correct for this feed please unmark it as a dup.

NaughtySquid
  • 1,947
  • 3
  • 29
  • 44

2 Answers2

1

You can use $variable['attribute_name'] to read the attribute data and for elements with dash and other characters in between the letters you can enclose it with braces and single quotes like I have done for the operating-systems element.

<?php
$url = 'http://www.shinyloot.com/feeds/games_on_sale';
$xml = simplexml_load_string(file_get_contents($url));
foreach ($xml->games->game as $game)
{
    $operating_system = array();
    foreach ($game->{'operating-systems'}->os as $os)
        $operating_system[] = $os;

    if (!in_array("Linux", $operating_system))
        continue;
    echo "Title: ", $game['title'], "\n";
    echo "URL: ", $game['url'], "\n";
    echo "MRSP: ", $game->mrsp, "\n";
    echo "Price: ", $game->price, "\n";
    echo "Discount: ", $game->{'discount-pct'}, "%\n";
    echo "Cover Image: ", $game->{'cover-image'}, "\n";
    echo "Header Image: ", $game->{'header-image'}, "\n";
    echo "Available for:\n";
    foreach ($operating_system as $os)
    {
        echo $os, "\n";
    }
    echo "==================================================\n\n";
}

An alternative way would be like this:

$operating_system = json_decode(json_encode($game->{'operating-systems'}), true);
if (!in_array("Linux", $operating_system['os']))
   continue;

Basically it transforms the result in JSON then convert it back into a simple associative array.

Prix
  • 19,417
  • 15
  • 73
  • 132
0

Okay so here is what I have for anyone wondering:

<?php
$url = 'http://www.shinyloot.com/feeds/games_on_sale';
$xml = simplexml_load_string(file_get_contents($url));
foreach ($xml->games->game as $game)
{
    $os_options = array();
    foreach ($game->{'operating-systems'}->os as $os)
    {
        $os_options[] = $os;
    }

    if (in_array("Linux", $os_options))
    {
        echo "Title: ", $game['title'], "\n";
        echo "URL: ", $game['url'], "\n";
        echo "Price: ", $game->price, "\n";
        echo "<br />==================================================<br />";
    }
}

Not sure if this is the best way to do it or not, but this allows me to filter by os.

Thanks to Prix.

NaughtySquid
  • 1,947
  • 3
  • 29
  • 44