普通网友 2013-08-24 18:52
浏览 21
已采纳

尝试使用php [duplicate]解析此xml提要

This question already has an answer here:

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.

</div>
  • 写回答

2条回答 默认 最新

  • duanmei1946 2013-08-24 19:26
    关注

    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'], "
    ";
        echo "URL: ", $game['url'], "
    ";
        echo "MRSP: ", $game->mrsp, "
    ";
        echo "Price: ", $game->price, "
    ";
        echo "Discount: ", $game->{'discount-pct'}, "%
    ";
        echo "Cover Image: ", $game->{'cover-image'}, "
    ";
        echo "Header Image: ", $game->{'header-image'}, "
    ";
        echo "Available for:
    ";
        foreach ($operating_system as $os)
        {
            echo $os, "
    ";
        }
        echo "==================================================
    
    ";
    }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?