从simple_xml数据设置数组

时间:2013-12-12 13:30:55

标签: php xml

我正在尝试使用以下代码从xml Feed创建标题数组:

$url = 'https://indiegamestand.com/store/salefeed.php';
$xml = simplexml_load_string(file_get_contents($url));

$on_sale = array();

foreach ($xml->channel->item as $game)
{
    echo $game->{'title'} . "\n";
    $on_sale[] = $game->{'title'};
}

print_r($on_sale);

echo $ game-> {'title'}。 “\ n” 个;返回正确的标题,但是当我将标题设置为数组时,我会发送垃圾邮件:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

    [1] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

    [2] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

设置此数组时我是否遗漏了某些内容?

1 个答案:

答案 0 :(得分:2)

使用此:

$on_sale[] = $game->{'title'}->__toString();

甚至更好(在我看来):

$on_sale[] = (string) $game->{'title'};

当您将对象添加到数组时,PHP不知道您想要字符串值,因此__toString()不会像echo调用中那样自动调用string。将对象强制转换为__toString()时,会自动调用$on_sale[] = (string) $game->title;

FYI:你也不需要花括号,这对我来说很好用:

{{1}}