SimpleXML 返回 0 元素

问题描述 投票:0回答:2

我从 Soap 请求中获取响应,并将其传递到新的 SimpleXML 构造中。

$response = $this->client->$method(array("Request" => $this->params));
$response_string = $this->client->__getLastResponse();
$this->response = new Classes_Result(new SimpleXMLElement($result));

如果我回显 $response_string,它会输出正确的 xml 字符串。这是一个片段,因为它很长。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body><GetClassesResponse xmlns="http://clients.mindbodyonline.com/api/0_5">      
    <GetClassesResult>
     <Status>Success</Status>
     <XMLDetail>Full</XMLDetail>
     <ResultCount>6</ResultCount>
     <CurrentPageIndex>0</CurrentPageIndex>
     <TotalPageCount>1</TotalPageCount>
     <Classes>
      <Class>
       <ClassScheduleID>4</ClassScheduleID>
       <Location>
        <SiteID>20853</SiteID>
  ....</soap:Envelope>

然而,当我尝试使用这个对象时,我会收到错误,或者如果我转储它输出的对象:

object(SimpleXMLElement)#51 (0)

知道为什么会发生这种情况吗?

php xml simplexml
2个回答
2
投票

您实际上并没有使用

$response_string
,并且您还没有在任何地方设置
$result
,您已将其传递给
new SimpleXMLElement($result)

也许您打算通过

$response_string
 使用 
simplexml_load_string()
字符串构建 SimpleXML 对象?

$response = $this->client->$method(array("Request" => $this->params));
$response_string = $this->client->__getLastResponse();
// Load XML via simplexml_load_string()
$this->response = new Classes_Result(simplexml_load_string($response_string));

// Or if you do expect a SimpleXMLElement(), pass in the string
$this->response = new Classes_Result(new SimpleXMLElement($response_string));

SOAP 响应的

<soap:Body>
元素的命名空间为 (
soap
)。要使用 SimpleXML 循环它,您必须提供正确的命名空间:

// After creating new SimpleXMLElement()
var_dump($this->response->children("http://schemas.xmlsoap.org/soap/envelope/"));

// class SimpleXMLElement#2 (1) {
//   public $Body =>
//   class SimpleXMLElement#4 (0) {
//  }
// }

要在主体上循环:

foreach ($this->response->children("http://schemas.xmlsoap.org/soap/envelope/") as $b) {
  $body_nodes = $b->children();
  // Get somethign specific
  foreach ($body_nodes->GetClassesResponse->GetClassesResult as $bn) {
    echo $bn->ResultCount . ", ";
    echo $bn->TotalPageCount;
  }
}
// 6, 1

0
投票

我有同样的问题,但在我的例子中,解决了仅用双引号引起来的字符串值的转换。

foreach($response->detail as $v) {
  echo "Title: {$v->title}";
}
© www.soinside.com 2019 - 2024. All rights reserved.