php - 从 simple_xml 数据设置数组

标签 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
                (
                )

        )

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

最佳答案

使用这个:

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

或者甚至更好(在我看来):

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

当您将对象添加到数组时,PHP 不知道您需要字符串值,因此 __toString() 不会像 echo< 中那样自动调用 调用。当您将对象转换为 string 时,会自动调用 __toString()

仅供引用:您也不需要大括号,这对我来说效果很好:

$on_sale[] =(字符串)$game->title;

关于php - 从 simple_xml 数据设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544919/

相关文章:

JSON over Diagnose 协议(protocol)

php - 使用 eval() 按 WordPress 的多个条件对多数组进行排序

PHP MySql 查询在更新后显示旧值

java - 使用 XSLT 将一个 JAXB 对象转换为另一个

xml - 从 groovy 中的 SOAP 响应中提取 CDATA

c# - Xml 反序列化 - 数组元素

php - Windows Server 2008 R2 中的 MySQL 查询执行时间大于标准 Windows 8.1 或 WIndows 10 操作系统中的执行时间

php - 如何从 MySQL/PHP 中获取每个科目的科目名称和错过的作业总数

php - 日期设置为默认 '1999-11-30'

c# - 如何将数据从 Windows 窗体保存到 XML 文件?