PHP:simplexml_load_string()强制数组 [英] PHP: simplexml_load_string() force array

查看:252
本文介绍了PHP:simplexml_load_string()强制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我是否可以强制SimpleXMLElement变量始终为数组吗?

Does anyone know if I can force a SimpleXMLElement variable to always be an array?

<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>
    <item>
        <id>2</id>
        <name>name 2</name>
    </item>
</result>

当通过simplexml_load_string()解析上述XML时,我得到以下对象

When parsing the above XML through simplexml_load_string() I get the following object

SimpleXMLElement Object
(
    [item] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [id] => 1
                [name] => name 1
            )
        [1] => SimpleXMLElement Object
             (
                [id] => 2
                [name] => name 2
            )
    )
)

这很棒,因为我可以遍历项目"并获取单个对象.但是,当item是一个条目时,如下所示,我会得到一个不同的对象结构,这会破坏我的循环,因为我开始循环遍历"id"和"name"而不是对象.

Which is great because I can loop through "item" and get the individual objects. But when item is a single entry, like below, I get a different object structure which ruins my loop becuase I start looping through "id" and "name" instead of objects.

<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>
</result>

SimpleXMLElement Object
(
    [item] => SimpleXMLElement Object
    (
           [id] => 1
           [name] => name 1    
    )

)

是否有通过"simplexml_load_string()"或通过重新构造XML来强制"item"成为数组的方法?

Is there anyway to force "item" to be an array with simplexml_load_string() or by re-structuring the XML?

推荐答案

您不需要将其作为数组,只需执行简单的检查即可.喜欢

You don't need to have that as an array, a simple check will do. Like

if(is_array($xml->result->item))
{
    //loop here
}
else
{
    //only one object
}

此外,无论有一个元素还是有多个元素,单个foreach都可以完成工作.例如

Also, a single foreach will get the job done whether there is one element or there are multiple. For example

<?php
$string="
<result>
    <item>
        <id>1</id>
        <name>name 1</name>
    </item>

</result>";

$xml = simplexml_load_string($string);

//print_r($xml);


foreach($xml->item as $item)
{
echo $item->id."\n";
}
?>

这对于多个项目也非常适用.见小提琴

That works perfectly fine for multiple items as well. See fiddle

小提琴

Fiddle

这篇关于PHP:simplexml_load_string()强制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆