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

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题