通过AWS PHP SDK响应循环/迭代

时间:2012-08-01 17:01:36

标签: php sdk amazon-web-services simplexml

我注意到,AWS PHP SDK的回复有时是一个结果的结果。

问题可能是因为我在处理CFSimpleXML / SimpleXML对象时缺乏知识。

我已经尝试了几种方法,但是每一种方法都相当困难,我所学到的是经过一段时间的做事而且看起来都很困难,那么你做错了。

发生了什么

使用describe_load_balancers

调用示例
<?php

$elb      = new AmazonELB();
$response = $elb->describe_load_balancers();

if ($response->isOK())
{
    foreach($response->body->LoadBalancerDescriptions() AS $loadBalancer)
    {
        print_r($loadBalancer);
    }
}
?>

如果它只有一个结果,则打印出如下内容:

CFSimpleXML Object
(
    [member] => CFSimpleXML Object
        (
            [SecurityGroups] => CFSimpleXML Object
                (
                )

            [LoadBalancerName] => LBName1
            [CreatedTime] => 2012-08-01T12:22:03.910Z
            ...
        )
)

如果它有多个结果,则打印出如下内容:

CFSimpleXML Object
(
    [member] => Array
        (
            [0] => CFSimpleXML Object
                (
                    [SecurityGroups] => CFSimpleXML Object
                        (
                        )

                    [LoadBalancerName] => LBName1
                    [CreatedTime] => 2012-08-01T12:22:03.910Z
                    ...
                )

            [1] => CFSimpleXML Object
                (
                    [SecurityGroups] => CFSimpleXML Object
                        (
                        )

                    [LoadBalancerName] => LBName2
                    [CreatedTime] => 2012-08-01T16:17:21.030Z
                    ...
                )
        )
)

如果只有一个结果,我想要的是什么

CFSimpleXML Object
(
    [member] => Array
        (
            [0] => CFSimpleXML Object
                (
                    [SecurityGroups] => CFSimpleXML Object
                        (
                        )

                    [LoadBalancerName] => LBName1
                    [CreatedTime] => 2012-08-01T12:22:03.910Z
                    ...
                )
        )
)

我试图遍历并查看member是否是一个数组,但它仍然将其作为CFSimpleXML对象返回,因此我无法检测print_r所说的数组。

我希望能够遍历列表,并在SimpleXML的代码中制作ELB模型,或者轻松迭代属性。

2 个答案:

答案 0 :(得分:2)

$elb      = new AmazonELB();
$response = $elb->describe_load_balancers();

foreach($response->body->LoadBalancerDescriptions() AS $item)
{
    foreach($item->member() AS $member)
    {
        print_r($member);
    }
}

打印

CFSimpleXML Object
(
[SecurityGroups] => CFSimpleXML Object
    (
    )

[LoadBalancerName] => LBName1
[CreatedTime] => 2012-08-01T12:22:03.910Z

编辑9/14/12:只是想快速更新并分享我发现有帮助的链接:Konrad Kiss' Code & Tech Rant: Listing AWS instances in PHP

答案 1 :(得分:0)

你可以利用$ response-&gt; body

的to_json,to_stdClass和to_array方法
<?php

require_once 'AWSSDKforPHP/sdk.class.php';

$ec2 = new AmazonEC2();

$response = $ec2->describe_instances(); 
$instances = $response->body->to_stdClass();

echo count($instances->reservationSet->item).PHP_EOL;

foreach ($instances->reservationSet->item as $reservation) {
    echo $reservation->instancesSet->item->instanceId.PHP_EOL; 
}

这已在此处讨论过:iterating over SimpleXML Objext PHP