我正在使用amazon API,我需要检查XML的状态。例如:
<GetMatchingProductForIdResult status="Success" IdType="UPC" Id="082686068055">
或
<GetMatchingProductForIdResult status="ClientError" IdType="UPC" Id="082686068055">
我如何编写检查状态是否为“成功”的代码? XML看起来像这样:
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult status="Success" IdType="UPC" Id="082686068055">
<Products>
<Product>
<Identifiers>
...
</Identifiers>
<AttributeSets>
</AttributeSets>
</Product>
</Products>
</GetMatchingProductForIdResult>
错误:
<GetMatchingProductForIdResult Id="082686035408" IdType="UPC" status="ClientError">
<Error>
<Type>Sender</Type>
<Code>InvalidParameterValue</Code>
<Message>Invalid UPC identifier 082686035408 for marketplace ATVPDKIKX0DER</Message>
</Error>
</GetMatchingProductForIdResult>
用于检索内容的PHP代码:
if(isset($items->Products->Product->AttributeSets->children($namespace['ns2'])->ItemAttributes->ListPrice->Amount)) {
$amount = $items->Products->Product->AttributeSets->children($namespace['ns2'])->ItemAttributes->ListPrice->Amount;
}else{
$amount = '0.00';
}
我能够创建此代码以获取产品的ID:
//$xml is an open XML file.
$items=$xml->GetMatchingProductForIdResult;
if(isset($items['Id'])){
$id = $items['Id'];
}else{
$id = 'No Id Found';
}
第一个标记保留在整个XML文件中。标签在文件末尾关闭。我正在使用SimpleXML打开,并从文件中获取所需的所有其他数据,但当<AttributeSets>
中的标记无效时,我总是会出错。我需要找到一种方法来避免这个问题。提前致谢。
答案 0 :(得分:1)
事实上,有很多方法可以去。但是,您只需要检测是否出现错误或成功:
<?php
$xmldata = <<<XML
<?xml version='1.0' ?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult status="Success" IdType="UPC" Id="082686068055">
....
</GetMatchingProductForIdResult>
</GetMatchingProductForIdResponse>
XML;
$xml = new SimpleXmlElement($xmldata);
$items = $xml->GetMatchingProductForIdResult;
$ERROR_FOUND = 'Error' == $items->attributes()->status;
if ($ERROR_FOUND) {
// do something on error, such as return or exit()...
}
// continue xml data parsing