什么是访问xml对象中的数据的正确方法

时间:2013-12-09 15:08:33

标签: php xml

我正在开发一个API项目,我将XML对象作为响应。响应可以在NewOrder对象中包含一个或多个产品(如下所示)。但是当我尝试使用foreach循环显示信息时,如果只有一个条目,则会中断。我猜这是因为object.how中不存在索引[0]我可以通过xml对象和显示,因为没有[0] i对象。或者如何在对象中添加索引[0]。

object(stdClass)#49 (1) {
["NewOrder"] => object(stdClass)#50 (12) {
["BTN"] => string(10) "XXXXXXXXXXXXXXXxx"
["PreOrderTransactionId"] => string(22) "XXXXXXXX"
["PartnerOrderId"] => string(17) "XXXXXXXXXXX"
["QwestOrderId"] => string(9) "N57395699"
["SalesCode"] => string(7) "XXXXXXXX"
["OrderStatus"] => string(7) "Pending"
["OrderStatusCode"] => string(4) "OPEN"
["OrderStatusSourceSystem"] => string(5) "CPLUS"
["OrderStatusMessage"] => string(0) ""
["OrderStatusDate"] => string(10) "2013-12-09"
["OrderStatusTime"] => string(8) "08:02:30"
["ProductFamily"] => array(3) {
  [0] => object(stdClass)#51 (2) {
    ["ProductFamilyName"] => string(7) "BUNDLE+"
    ["ProductLines"] => object(stdClass)#52 (3) {
      ["WTN"] => string(10) "3033689919"
      ["AppointmentDate"] => string(10) "2013-12-20"
      ["Products"] => object(stdClass)#53 (5) {
        ["ProductName"] => string(36) "INTERNET 100+ MBPS & HOME PHONE PLUS"
        ["Usoc"] => string(5) "BBBVC"
        ["Quantity"] => string(1) "1"
        ["Action"] => string(1) "I"
        ["Status"] => string(4) "OPEN"
      }
    }
  }
 }
}
}

我尝试过以下但是没有用:

if (!is_array($this->Orders->NewOrder)) {
$this->Order->NewOrder = array($this->Orders->NewOrder["NewOrder"]);

}
foreach ($this->Orders->NewOrder as $order){?>

我收到以下错误: 致命错误:无法在

中使用stdClass类型的对象作为数组

2 个答案:

答案 0 :(得分:1)

我认为你的NewOrder只是一个数组,如果它包含多个对象。在循环之前使用类似的东西:

if (!is_array(yourObject["NewOrder"])) {
    yourObject["NewOrder"] = array(yourObject["NewOrder"]);
}

答案 1 :(得分:0)

SoapClient有一个始终创建数组的选项,即使这里只有一个元素。

return new SoapClient(
  '...',
  array(
    'location' => '...',
    /.../
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS
  )
);