尝试使用php解析此xml提要


Trying to parse this xml feed using php

我想知道如何用php解析这个xml提要?

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

我知道我可以用这个开始:

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

从那以后,我不确定解析它的最佳方式是它是一个更复杂的内部有多个数组的方法。

此外,这不是重复的,这是一个特定的情况,你批量链接的答案对此提要不正确,请将其取消标记为重复。

您可以使用$variable['attribute_name']读取属性数据,对于字母之间带有短划线和其他字符的元素,您可以使用大括号和单引号将其括起来,就像我对operating-systems元素所做的那样。

<?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";
}

另一种方式是这样的:

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

基本上,它将结果转换为JSON,然后将其转换回一个简单的关联数组。

好的,下面是我为任何想知道的人准备的:

<?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 />";
    }
}

不确定这是否是最好的方法,但这允许我通过操作系统进行过滤。

感谢Prix。