阅读PHP中的Amazon Cloudfront API结果

时间:2013-04-17 18:44:53

标签: php api amazon-web-services

我有一个PHP脚本,通过API向亚马逊的Cloudfront提交Invalidation请求。

我可以捕获响应,但它的回复基本上看起来像这样:

HTTP/1.0 201 Created
Content-Type: text/xml
Location: https://cloudfront.amazonaws.com/2012-07-01/distribution/distribution ID/invalidation/invalidation ID

<Invalidation xmlns="http://cloudfront.amazonaws.com/doc/2012-07-01/">
   <Id>IDFDVBD632BHDS5</Id>
   <Status>InProgress</Status>
   <CreateTime>2013-04-16T19:37:58Z</CreateTime>   
   <InvalidationBatch>
      <Paths>
         <Items>
            <Path>/image1.jpg</Path>
         </Items>
      </Paths>
      <CallerReference>20130416090001</CallerReference>
   </InvalidationBatch>
</Invalidation>

我基本上只想获取状态值,我想我可以通过Regex或一些字符串操作来实现,但我假设有一种更好的方法将返回的数据转换为对象并正确访问它。

我试过了:

$dom = new DOMDocument();
$dom->loadXML($data);

但是$ data不起作用,因为它实际上包含标题部分“HTTP / 1.0 201 ...”

任何人都知道处理此问题的正确方法吗?

3 个答案:

答案 0 :(得分:5)

你用的是什么脚本?您是否考虑过使用AWS SDK for PHP(https://github.com/aws/aws-sdk-php)?

使用AWS SDK for PHP,您可以执行以下操作:

// Instantiate a CloudFront client
$cloudfront = \Aws\CloudFront\CloudFrontClient::factory(array(
    'key'    => 'your-aws-access-key-id',
    'secret' => 'your-aws-secret-key',
));

// Get the status of an invalidation
$invalidationStatus = $cloudfront->getInvalidation(array(
    'DistributionId' => 'your-distribution-id',
    'Id'             => 'your-invalidation-id',
))->get('Status');

答案 1 :(得分:1)

通常Http客户端库应该这样做,你没有提到使用过的。

仍在解析该响应应该简单如下:

$dom->loadXML(substr($data, strpos("\n\n", $data)+2))

答案 2 :(得分:-2)

通过执行以下操作来解决这个问题。

$resp = substr($resp, strpos($resp, "\r\n\r\n")+4); // This strips out the header

$outputxml = simplexml_load_string($resp); // Converts it to an object in PHP which can be fed back more easily