php 循环遍历 SimpleXML 对象,或将整个对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/871422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:10:01  来源:igfitidea点击:

Looping through a SimpleXML object, or turning the whole thing into an array

phpamazon-web-servicessimplexmlamazon-simpledb

提问by Coffee Cup

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

我正在尝试解决如何遍历返回的 SimpleXML 对象。

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

我正在使用一个名为Tarzan AWS的工具包,它连接到 Amazon Web Services(SimpleDB、S3、EC2 等)。我专门使用 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.

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

The Tarzan AWS documentation says this:

Tarzan AWS 文档是这样说的:

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.

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

Here's a sample of the returned SimpleXML object:

下面是返回的 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
                                                )

                                        )

                                )

                        )

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.

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

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

或者,你如何将整个shebang变成一个数组?

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

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

回答by Tim Lytle

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

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

//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.

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

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.

虽然上面的示例代码循环访问 SimpleXML 对象中的数组($SimpleXML->body->QueryWithAttributesResult->Item),但您也可以循环访问 SimpleXML 对象(比如 $SimpleXML->body->QueryWithAttributesResult->Item[ 0]),这会给你每个对象的属性。

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.

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

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

如果你愿意,这应该从你的 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.

回答by Sebastian

get_object_vars($simpleXMLElement);

回答by cruzanmo

one slight addition for for the PHP 5.2 fix.

PHP 5.2 修复的一个小补充。

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

回答by cruzanmo

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.

对于不包含 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));

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

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

回答by Hasenpriester

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.

我发现的几乎所有示例都参考了一个您已经知道节点的特定示例。以下函数会将 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;
}

回答by Jonathan Galpin

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;
}