普通网友 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条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程