我想知道如何用php解析这个xml feed?
http://www.shinyloot.com/feeds/games_on_sale
我知道我可以用它开头:
$shinyloot = simplexml_load_file('http://www.shinyloot.com/feeds/games_on_sale');
从那里我不确定解析它的最佳方法是它是一个内部有多个数组的更复杂的方法。
另外这不是重复的,这是一个特定的案例,而且您批量链接的答案对于此Feed不正确请将其标记为副本。
答案 0 :(得分:1)
您可以使用$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中转换结果,然后将其转换回简单的关联数组。
答案 1 :(得分:0)
好的,这就是我对任何想知道的人的看法:
<?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。