循环访问 SimpleXML 对象,或将整个对象转换为数组

发布于 2024-07-20 16:27:47 字数 5475 浏览 15 评论 0原文

我正在尝试弄清楚如何迭代返回的 SimpleXML 对象。

我正在使用一个名为 Tarzan AWS 的工具包,它连接到 Amazon Web Services(SimpleDB、S3、EC2 等) )。 我专门使用 SimpleDB。

我可以将数据放入 Amazon SimpleDB 服务中,也可以将其取回。 我只是不知道如何处理返回的 SimpleXML 对象。

Tarzan AWS 文档是这样说的:

查看响应以浏览响应的标题和正文。 请注意,这是一个对象,而不是数组,并且主体是一个 SimpleXML 对象。

下面是返回的 SimpleXML 对象的示例:

 [body] => SimpleXMLElement Object
        (
            [QueryWithAttributesResult] => SimpleXMLElement Object
                (
                    [Item] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [Name] => message12413344443260
                                    [Attribute] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [Name] => active
                                                    [Value] => 1
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [Name] => user
                                                    [Value] => john
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [Name] => message
                                                    [Value] => This is a message.
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [Name] => time
                                                    [Value] => 1241334444
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [Name] => id
                                                    [Value] => 12413344443260
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [Name] => ip
                                                    [Value] => 10.10.10.1
                                                )

                                        )

                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [Name] => message12413346907303
                                    [Attribute] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [Name] => active
                                                    [Value] => 1
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [Name] => user
                                                    [Value] => fred
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [Name] => message
                                                    [Value] => This is another message
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [Name] => time
                                                    [Value] => 1241334690
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [Name] => id
                                                    [Value] => 12413346907303
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [Name] => ip
                                                    [Value] => 10.10.10.2
                                                )

                                        )

                                )

                        )

那么我需要什么代码来获取每个对象项? 我想循环遍历它们中的每一个并像处理返回的 mySQL 查询一样处理它。 例如,我可以查询 SimpleDB,然后循环访问 SimpleXML,以便可以在页面上显示结果。

或者,如何将整个 shebang 转换为数组?

我是 SimpleXML 的新手,所以如果我的问题不够具体,我深表歉意。

I'm trying to work out how to iterate though a returned SimpleXML object.

I'm using a toolkit called Tarzan AWS, which connects to Amazon Web Services (SimpleDB, S3, EC2, etc). I'm specifically using SimpleDB.

I can put data into the Amazon SimpleDB service, and I can get it back. I just don't know how to handle the SimpleXML object that is returned.

The Tarzan AWS documentation says this:

Look at the response to navigate through the headers and body of the response. Note that this is an object, not an array, and that the body is a SimpleXML object.

Here's a sample of the returned SimpleXML object:

 [body] => SimpleXMLElement Object
        (
            [QueryWithAttributesResult] => SimpleXMLElement Object
                (
                    [Item] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [Name] => message12413344443260
                                    [Attribute] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [Name] => active
                                                    [Value] => 1
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [Name] => user
                                                    [Value] => john
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [Name] => message
                                                    [Value] => This is a message.
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [Name] => time
                                                    [Value] => 1241334444
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [Name] => id
                                                    [Value] => 12413344443260
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [Name] => ip
                                                    [Value] => 10.10.10.1
                                                )

                                        )

                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [Name] => message12413346907303
                                    [Attribute] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [Name] => active
                                                    [Value] => 1
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [Name] => user
                                                    [Value] => fred
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [Name] => message
                                                    [Value] => This is another message
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [Name] => time
                                                    [Value] => 1241334690
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [Name] => id
                                                    [Value] => 12413346907303
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [Name] => ip
                                                    [Value] => 10.10.10.2
                                                )

                                        )

                                )

                        )

So what code do I need to get through each of the object items? I'd like to loop through each of them and handle it like a returned mySQL query. For example, I can query SimpleDB and then loop though the SimpleXML so I can display the results on the page.

Alternatively, how do you turn the whole shebang into an array?

I'm new to SimpleXML, so I apologise if my questions aren't specific enough.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

凉城凉梦凉人心 2024-07-27 16:27:47

您可以在 foreach 循环中使用 SimpleXML 对象(或其属性)。 如果您想循环遍历所有“记录”,可以使用类似这样的方法来访问和显示数据:

//Loop through all the members of the Item array 
//(essentially your two database rows).
foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
    //Now you can access the 'row' data using $Item in this case 
    //two elements, a name and an array of key/value pairs
    echo $Item->Name;
    //Loop through the attribute array to access the 'fields'.
    foreach($Item->Attribute as $Attribute){
        //Each attribute has two elements, name and value.
        echo $Attribute->Name . ": " . $Attribute->Value;
    }
}

请注意,$Item将是一个SimpleXML对象,$Attribute也是如此,因此它们需要作为对象而不是数组来引用。

虽然上面的示例代码循环遍历 SimpleXML 对象中的数组 ($SimpleXML->body->QueryWithAttributesResult->Item),但您也可以循环遍历 SimpleXML 对象(例如 $SimpleXML->body->Item)。 QueryWithAttributesResult->Item[0]),这将为您提供对象的每个属性。

SimpleXML 对象的每个子元素都是一个 XML 实体。 如果 XML 实体(标签)不是唯一的,则该元素只是表示每个实体的 SimpleXML 对象的数组。

如果您愿意,这应该从您的 SimpleXML 对象创建一个更常见的行/字段数组(或让您接近):

foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
    foreach($Item->Attribute as $Attribute){
        $rows[$Item->Name][$Attribute->Name] = $Attribute->Value;
    }
}

//Now you have an array that looks like:
$rows['message12413344443260']['active'] = 1;
$rows['message12413344443260']['user'] = 'john';
//etc.

You can use the SimpleXML object (or its properties) in a foreach loop. If you want to loop through all the 'records' something like this can be used to access and display the data:

//Loop through all the members of the Item array 
//(essentially your two database rows).
foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
    //Now you can access the 'row' data using $Item in this case 
    //two elements, a name and an array of key/value pairs
    echo $Item->Name;
    //Loop through the attribute array to access the 'fields'.
    foreach($Item->Attribute as $Attribute){
        //Each attribute has two elements, name and value.
        echo $Attribute->Name . ": " . $Attribute->Value;
    }
}

Note that $Item will be a SimpleXML object, as is $Attribute, so they need to be referenced as objects, not arrays.

While the example code above is looping through the arrays in the SimpleXML object ($SimpleXML->body->QueryWithAttributesResult->Item), you can also loop through a SimpleXML object (say $SimpleXML->body->QueryWithAttributesResult->Item[0]), and that would give you each of the object's properties.

Each child element of a SimpleXML object is an XML entity. If the XML entity (tag) is not unique, then the element is simply an array of SimpleXML objects representing each entity.

If you want, this should create a more common row/fields array from your SimpleXML object (or get you close):

foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
    foreach($Item->Attribute as $Attribute){
        $rows[$Item->Name][$Attribute->Name] = $Attribute->Value;
    }
}

//Now you have an array that looks like:
$rows['message12413344443260']['active'] = 1;
$rows['message12413344443260']['user'] = 'john';
//etc.
羁客 2024-07-27 16:27:47
get_object_vars($simpleXMLElement);
get_object_vars($simpleXMLElement);
孤独难免 2024-07-27 16:27:47

针对 PHP 5.2 修复的一个小补充。

$response_array = json_decode(json_encode($response),true);

one slight addition for for the PHP 5.2 fix.

$response_array = json_decode(json_encode($response),true);
放肆 2024-07-27 16:27:47

对于不包含 CDATA 部分的 XML 响应(例如 Amazon/Tarzan),假设您有 PHP 5.2 或更高版本,则可以使用以下内容。

// Get a SimpleXML response back from Tarzan
$s3 = new AmazonS3();
$response = $s3->list_buckets();

// Convert SimpleXML to Array in PHP 5.2.
$response_array = json_decode(json_encode($response));

这将成为 Tarzan 下一个主要版本 (CloudFusion 2.5) 中所有对象都可用的标准实用程序。

In the case of XML responses that DON'T contain CDATA sections (like Amazon's/Tarzan's), you can use the following assuming you have PHP 5.2 or newer.

// Get a SimpleXML response back from Tarzan
$s3 = new AmazonS3();
$response = $s3->list_buckets();

// Convert SimpleXML to Array in PHP 5.2.
$response_array = json_decode(json_encode($response));

This will be a standard utility available to all objects in the next major version of Tarzan (CloudFusion 2.5).

放肆 2024-07-27 16:27:47

我发现的几乎所有示例都引用了您已经知道节点的特定示例。
以下函数会将 SimpleXMLElement 转换为数组,而无需知道节点名称或它们是否有子节点。 也可以与 CDATA 部分一起正常工作。

function parseXML(SimpleXMLElement $xml) : array
{
    $array = [];

    foreach(iterator_to_array($xml, TRUE) as $key => $value)
        $array[$key] = ($value->count() > 1) ? parseXML($value) : (string)$value;

    return $array;
}

Almost all examples I found refer to a specific example where you already know the nodes.
Following function will convert a SimpleXMLElement into an array without knowing Node Names or if they have childs or not. Will also work fine with CDATA Sections.

function parseXML(SimpleXMLElement $xml) : array
{
    $array = [];

    foreach(iterator_to_array($xml, TRUE) as $key => $value)
        $array[$key] = ($value->count() > 1) ? parseXML($value) : (string)$value;

    return $array;
}
苍风燃霜 2024-07-27 16:27:47

这有效:

// $result is a Simple XML object

$result = convertSimpleXMLToArray($result);

function convertSimpleXMLToArray($xml)
{
    if(class_basename($xml) == 'SimpleXMLElement')
    {
        $xml = get_object_vars($xml);
        foreach($xml as $key => $value)
        {
            if(class_basename($value) == 'SimpleXMLElement') $xml[$key] = convertSimpleXMLToArray($value);
        }
    }

    return $xml;
}

This worked:

// $result is a Simple XML object

$result = convertSimpleXMLToArray($result);

function convertSimpleXMLToArray($xml)
{
    if(class_basename($xml) == 'SimpleXMLElement')
    {
        $xml = get_object_vars($xml);
        foreach($xml as $key => $value)
        {
            if(class_basename($value) == 'SimpleXMLElement') $xml[$key] = convertSimpleXMLToArray($value);
        }
    }

    return $xml;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文