PHP SoapClient не получает подструктуры - PullRequest
0 голосов
/ 20 мая 2019

Я пытаюсь получить ответ службы SOAP, но не могу получить данные вложенных коллекций. Когда я вызываю метод ws с использованием программного обеспечения мыльного клиента, я получаю следующий ответ:

<WSGLMSuit.METHODNAME xmlns="http://tempuri.org/">
         <Sdtpolizadetalle>
            <Empresa>1</Empresa>
            <DscEmpresa>TEST</DscEmpresa>
            <Rama>22</Rama>
            <DscRama>COMBINADO FAMILIAR</DscRama>
            <Poliza>000000</Poliza>
            <DscRiesgo/>
            <InicioVigencia>2019-03-18</InicioVigencia>
            <FinVigencia>2019-09-18</FinVigencia>
            <Productor>3311</Productor>
            <NombreProductor>TEST</NombreProductor>
            <Tomador>
               <CodTomador>336028</CodTomador>
               <NombreTomador>TEST</NombreTomador>
               <Domicilio>SAAVEDRA 1174 Dpto. 0</Domicilio>
               <Localidad>TRES ARROYOS</Localidad>
               <CodigoPostal>7500</CodigoPostal>
            </Tomador>
            <DscMoneda>PESOS</DscMoneda>
            <CantidadCuotas>3</CantidadCuotas>
            <Suplementos>
               <Suplemento>
                  <Suplemento>0</Suplemento>
                  <TipoOperacion>02</TipoOperacion>
                  <SubTipoOperacion>000</SubTipoOperacion>
                  <DscOperacion>GENERAL</DscOperacion>
                  <InicioVigencia>2019-03-18</InicioVigencia>
                  <FinVigencia>2019-09-18</FinVigencia>
                  <Prima>2515.95</Prima>
                  <Premio>3104.68</Premio>
                  <Cuotas>
                     <Cuota>
                        <NroCuota>1</NroCuota>
                        <Vencimiento>2019-03-18</Vencimiento>
                        <Estado>Pagada</Estado>
                        <Importe>519.68</Importe>
                        <NroCupon>1</NroCupon>
                     </Cuota>
                     <Cuota>
                        <NroCuota>2</NroCuota>
                        <Vencimiento>2019-04-18</Vencimiento>
                        <Estado>Vencida</Estado>
                        <Importe>517.00</Importe>
                        <NroCupon>2</NroCupon>
                     </Cuota>
                     <Cuota>
                        <NroCuota>3</NroCuota>
                        <Vencimiento>2019-05-18</Vencimiento>
                        <Estado>Impaga</Estado>
                        <Importe>517.00</Importe>
                        <NroCupon>3</NroCupon>
                     </Cuota>
                  </Cuotas>
               </Suplemento>
            </Suplementos>
         </Sdtpolizadetalle>
         <Sesionexpirada>false</Sesionexpirada>
      </WSGLMSuit.METHODNAMEResponse>

Итак, я сделал функцию в PHP с классом SoapClient, чтобы сделать тот же запрос и получить результат, проанализированный как JSON, но он не дает мне коллекцию «Suplementos» и ее данные.

{
    "Sdtpolizadetalle": {
        "Empresa": 1,
        "DscEmpresa": "TEST",
        "Rama": 22,
        "DscRama": "COMBINADO FAMILIAR",
        "Poliza": 129031,
        "DscRiesgo": "",
        "InicioVigencia": "2019-03-18",
        "FinVigencia": "2019-09-18",
        "Productor": 3311,
        "NombreProductor": "TEST",
        "Tomador": {
            "CodTomador": 336028,
            "NombreTomador": "TEST",
            "Domicilio": "SAAVEDRA 1174 Dpto. 0",
            "Localidad": "TRES ARROYOS",
            "CodigoPostal": "7500"
        },
        "DscMoneda": "PESOS",
        "CantidadCuotas": 3,
        "Suplementos": {} // <--- HERE IS THE ISSUE
    },
    "Sesionexpirada": false
}

Функция PHP:

$wsdl = "http://wsdlservice.org?wsdl";
  $params = $request->getParsedBody();

  $options = array(
    'soap_version' => SOAP_1_2,
    'style'        => SOAP_DOCUMENT,
    'use'          => SOAP_LITERAL,
    'exceptions'   => true,
    'trace'        => 1,
    'cache_wsdl'   => WSDL_CACHE_NONE,
    'encoding'     => 'UTF-8'
  );

  $soap = new SoapClient($wsdl, $options);

  $clientRes = $soap->METHODNAME($params);

  return json_encode($clientRes, JSON_PRETTY_PRINT);

1 Ответ

0 голосов
/ 23 мая 2019

Наконец-то я получил решение.Я нашел функцию для разбора XML-строки в массив.Поэтому я получаю ответ в виде XML, сохраняю его в файл и анализирую с помощью этой функции.Код лучше слов:

function xmlToArray($xml, $options = array())
{
  $defaults       = array(
    'namespaceSeparator' => ':',
    'attributePrefix'    => '@',
    'alwaysArray'        => array(),
    'autoArray'          => true,
    'textContent'        => '$',
    'autoText'           => true,
    'keySearch'          => false,
    'keyReplace'         => false
  );
  $options        = array_merge($defaults, $options);
  $namespaces     = $xml->getDocNamespaces();
  $namespaces[''] = null;

  $attributesArray = array();
  foreach ($namespaces as $prefix => $namespace) {
    foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
      if ($options['keySearch']) $attributeName =
        str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
      $attributeKey                   = $options['attributePrefix']
        . ($prefix ? $prefix . $options['namespaceSeparator'] : '')
        . $attributeName;
      $attributesArray[$attributeKey] = (string)$attribute;
    }
  }

  $tagsArray = array();
  foreach ($namespaces as $prefix => $namespace) {
    foreach ($xml->children($namespace) as $childXml) {
      $childArray = xmlToArray($childXml, $options);
      list($childTagName, $childProperties) = each($childArray);

      if ($options['keySearch'])
        $childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);

      if ($prefix)
        $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;

      if (!isset($tagsArray[$childTagName])) {
        $tagsArray[$childTagName] =
          in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
            ? array($childProperties)
            : $childProperties;
      } elseif (
        is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
        === range(0, count($tagsArray[$childTagName]) - 1)
      ) {
        $tagsArray[$childTagName][] = $childProperties;
      } else {
        $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
      }
    }
  }

  $textContentArray = array();
  $plainText        = trim((string)$xml);
  if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;

  $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
    ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;

  return array(
    $xml->getName() => $propertiesArray
  );
}

$params  = array('key' => 'value') // params needed to make the request
$options = array(
  'trace'      => 1,
  'exceptions' => true
);

try {
  $soap = new SoapClient($url, $options);
  $soap->method($params); // replace method name
  $xmlResponse = $soap->__getLastResponse();
} catch (Exception $e) {
  die(
  json_encode(
    [
      'error' => 'Cannot request to WS. ' . $e->getMessage()
    ]
  )
);

// save the response into an xml file for parse 
// it and return its content as json
if (file_put_contents('response.xml', $xmlResponse)) {
  $xmlNode   = simplexml_load_file($this->tempPath);
  $arrayData = xmlToArray($xmlNode);
  unlink('response.xml');
  return json_encode($arrayData, JSON_PRETTY_PRINT);
} else {
  return json_encode(['error' => 'Error saving the response into file.']);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...