Soap error encoding violation of encoding rules

Guys, I'm stuck, banging my head off the desk for the past few hours. I am trying to consume a service, and I have 8 other functions that I call that are almost IDENTICAL in nature to this one, bu...

Guys, I’m stuck, banging my head off the desk for the past few hours.

I am trying to consume a service, and I have 8 other functions that I call that are almost IDENTICAL in nature to this one, but this one, results in a ‘SOAP-ERROR: Encoding: Violation of encoding rules’ error.

Heres the function call (wsdl omitted for security):

    function CanLoadProduct($data){

    $client = new SoapClient('wsdl-url');

    $params = array('username'   => $this->username,
                    'password'  => $this->password,
                    'prod'      => $data['productid'],
                    'mdn'       => $data['mdn']);

    try {
        $reply = $client->__soapCall("CanLoadProduct", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        print_r($params);
        die();
    }

    if( $reply['result'] == 1 ){
        return TRUE;        // 1 = true
    } else {
        return FALSE;
    }

}

Ok so this function, connects to a webservice, the required elements are:
username, password, prod, mdn, all 4 of which I supply as part of the $params array. Username/Pass are defined earlier, and do work fine, as the other 8 functions consume the web service without any problems.

The $data[] array (that I pass to the function), contains:
$data[‘productid’]
$data[‘mdn’]
nothing else is used.

I am getting

SOAP-ERROR: Encoding: Violation of encoding rules

for some unexplained reason, and Googling this error gets me nowhere. Anyone else run into this? Running PHP 5.2.9-2. The strange thing is this is identical to this function which works 100%:

    function GetPIN($productid){

    $client = new SoapClient('wsdl-url');

    $params = array('username'  => $this->username,
                    'password'  => $this->password,
                    'prod'      => $productid);

    try {
        $reply = $client->__soapCall("GetPIN", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        die();
    }
        return $reply;
}

Here is the WSDL (should have posted this first):

<?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" 
    xmlns:tns="ready:test" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
    xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="ready:test">
<types>
<xsd:schema targetNamespace="ready:test"
>
 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
</xsd:schema>
</types>
<message name="CanLoadProductRequest">
  <part name="username" type="xsd:string" />
  <part name="password" type="xsd:string" />
  <part name="prod" type="xsd:string" />    
  <part name="mdn" type="xsd:string" />
  <part name="esn" type="xsd:string" /></message>
<message name="CanLoadProductResponse">
  <part name="result" type="xsd:int" /></message>
<portType name="CanLoadProductPortType">
  <operation name="CanLoadProduct">
    <input message="tns:CanLoadProductRequest"/>
    <output message="tns:CanLoadProductResponse"/>
  </operation>
</portType>

<binding name="CanLoadProductBinding" type="tns:CanLoadProductPortType">
  <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
  <operation name="CanLoadProduct">
    <soap:operation soapAction="{url-removed}" style="rpc"/>
    <input>
        <soap:body use="encoded" namespace="" 
           encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </input>
    <output>
        <soap:body use="encoded" namespace="" 
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </output>
  </operation>
</binding>
<service name="CanLoadProduct">
  <port name="CanLoadProductPort" binding="tns:CanLoadProductBinding">

    <soap:address location="{url-removed}"/>
  </port>
</service>
</definitions>

I am trying to use Yii to provide a web service. The auto-generated wsdl is below. I can successfully consume the web service from the command line, but through a web browser, I get

SOAP-ERROR: Encoding: Violation of encoding rules

I am new to SOAP, so I am not sure how to debug the problem. Here is the PHP code I am using to consume the web service:

<?php
    $client=new SoapClient('{url omitted for security}',
        array('trace'=>1,'exceptions'=>1));
    try {
        $result = $client->getPerson(90043412);
        var_dump($result);
    } catch (SoapFault $fault) {
        echo $fault->getMessage() . '<br />';
        echo 'REQUEST <br />';
        echo '<pre>';
        echo $client->__getLastRequestHeaders();
        echo $client->__getLastRequest();
        echo '</pre>';
        echo 'RESPONSE <br />';
        echo '<pre>';
        echo $client->__getLastResponseHeaders();
        echo $client->__getLastResponse();
        echo '</pre>';
        echo 'TRACE <br />';
        echo '<pre>';
        var_dump($fault->getTrace());
        echo '</pre>';
    }
?>

Here is the WSDL:

<?xml version="1.0" encoding="UTF-8"?> 
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="urn:PersonControllerwsdl" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" name="PersonController" targetNamespace="urn:PersonControllerwsdl">
    <wsdl:types>
        <xsd:schema targetNamespace="urn:PersonControllerwsdl">
            <xsd:complexType name="Person">
                <xsd:all>
                    <xsd:element name="PIDM" type="xsd:integer"/>
                    <xsd:element name="FirstName" type="xsd:string"/>
                    <xsd:element name="MiddleName" type="xsd:string"/>
                    <xsd:element name="LastName" type="xsd:string"/>
                    <xsd:element name="PrefFirstName" type="xsd:string"/>
                    <xsd:element name="CPOBox" type="xsd:string"/>
                    <xsd:element name="Classification" type="xsd:string"/>
                    <xsd:element name="Email" type="xsd:string"/>
                    <xsd:element name="PhotoFile" type="xsd:string"/>
                </xsd:all>
            </xsd:complexType>
        </xsd:schema>
    </wsdl:types>
    <wsdl:message name="getPersonRequest">
        <wsdl:part name="PIDM" type="xsd:int"/>
    </wsdl:message>
    <wsdl:message name="getPersonResponse">
        <wsdl:part name="return" type="tns:Person"/>
    </wsdl:message>
    <wsdl:portType name="PersonControllerPortType">
        <wsdl:operation name="getPerson">
            <wsdl:documentation></wsdl:documentation>
            <wsdl:input message="tns:getPersonRequest"/>
            <wsdl:output message="tns:getPersonResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="PersonControllerBinding" type="tns:PersonControllerPortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="getPerson">
            <soap:operation soapAction="urn:PersonControllerwsdl#getPerson" style="rpc"/>
            <wsdl:input>
                <soap:body use="encoded" namespace="urn:PersonControllerwsdl" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="encoded" namespace="urn:PersonControllerwsdl" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="PersonControllerService">
        <wsdl:port name="PersonControllerPort" binding="tns:PersonControllerBinding">
            <soap:address location="https://localhost/whoswho/person/service?ws=1"/>
        </wsdl:port>
    </wsdl:service>
</definitions> 

asked Apr 12, 2011 at 16:57

nhavens's user avatar

2

It is possible that the SOAP request is incorrectly formatted. I’ve been using SoapUI and by default all the parameters are set to ‘?’ initially, if you make this request PHP will fail and respond with the error message you have reported. You cannot catch this, because no exception is thrown, this is because it is a fatal error.

You can set your own error handler for this situation using the set_error_handler() function http://php.net/manual/en/function.set-error-handler.php

answered Apr 13, 2011 at 18:01

Easen's user avatar

EasenEasen

2961 silver badge5 bronze badges

I was working to update my PHP version to 5.6.26 and this error pop-up on my web services calls. After a while, I found the issue could be fixed commenting in the PHP.ini file this line:

;always_populate_raw_post_data = -1

Reviewing the documentation, this option is deprecated in this version.

I hope this comment save time to someone.

answered Sep 29, 2016 at 15:56

pasachova's user avatar

If I host the consume script on a different server than the one hosting the web service, it functions properly. Since web services are designed for machine-machine communication more than a machine talking to itself, this seems like an adequate solution.

answered Apr 13, 2011 at 17:47

nhavens's user avatar

nhavensnhavens

2521 gold badge3 silver badges11 bronze badges

I know this is an old thread, but if you come across it as I did trying to figure out this problem, you might try setting the soap:address to http://127.0.0.1 instead of http://localhost. I’ve run into a few other forums where this helped.

answered Feb 2, 2012 at 19:38

CrimsonKissaki's user avatar

1

Содержание

  1. Network Programming in .NET
  2. Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules
  3. SOAP-ERROR: Кодирование: нарушение правил кодирования?
  4. SOAP-ERROR: Кодирование: Нарушение правил кодирования?
  5. 11 ответы
  6. SOAP-ERROR: Кодировка: Нарушение правил кодирования?
  7. 9 ответов
  8. SOAP Error #393
  9. Comments

Network Programming in .NET

Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules

WTF?, why the hell is every PHP developer saying my webservice is returning Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules – and there’s no problem with those using .NET, or parsing the XML response over HTTP GET/POST

Ok, let’s break down the problem.
1. It’s not a problem with PHP,it’s your WSDL, so here’s how to diagnose it.

Take this simple code snippet

$client = new SoapClient(“http://www.regcheck.org.uk/api/reg.asmx?wsdl”);
$params = array (
“RegistrationNumber” => “TNZ6972”,
“username” => “**Your Username**”
);
$response = $client->__soapCall(‘Check’, array($params));
print_r($response);

Now, take a copy of the WSDL, and save it as a text file, so you can edit it easily, i.e.

http://www.regcheck.org.uk/php.wsdl , then using HTML style comments, take out everything you can until you get a minimum working version. – i.e. a call that returns “something“, not all the data, but “something

I had a hunch it was the VehicleData object, since it was the most complex type in the response, so I commented that out – and I now had a minimum working version.

After that, I progressively commented out elements within the VehicleData type, until I got my maximum working version – i.e. as much data as possible without it breaking.

At that point, I hit upon this:

Which was the point at which the webservice stopped returning data, and starting throwing the Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules – and it did look odd, since I new that “CarModel” should be a string, not an integer.

Looking at the underlying C# code, the error was obvious

[System.Xml.Serialization.XmlTextAttribute(DataType=”integer“)]
public string Value <

There is no way that Value could both be a string and an integer, so I changed it to

Источник

SOAP-ERROR: Кодирование: нарушение правил кодирования?

Ребята, я застрял, ударив головой из-за стола в течение последних нескольких часов.

Я пытаюсь использовать службу, и у меня есть еще 8 других функций, которые я называю почти идентичными по своему характеру, но это приводит к ошибке «Ошибка SOAP-ERROR: кодирование: нарушение правил кодирования».

Heres вызов функции (wsdl пропущен для обеспечения безопасности):

Итак, эта функция, подключается к веб-сервису, необходимыми элементами являются: имя пользователя, пароль, prod, mdn, все 4 из которых я поставляю как часть массива $ params. Имя пользователя / пароль определены раньше и работают нормально, так как остальные 8 функций без проблем обрабатывают веб-службу.

Массив $ data [] (который я передаю функции) содержит: $ data [‘productid’] $ data [‘mdn’] ничего не используется.

по какой-то необъяснимой причине, и Гуглинг эта ошибка не дает мне нигде. Кто-нибудь еще сталкивается с этим? Запуск PHP 5.2.9-2. Странно то, что эта функция идентична этой функции, которая работает на 100%:

Вот WSDL (должен был опубликовать это в первую очередь):

Похоже, что у вас есть несоответствие типа где-то, либо при сборке вашего запроса (один из параметров не относится к строке типа), либо сервер возвращает что-то иное, чем int (нарушая определение ответа WSDL и тем самым заставляя клиента рассматривать ответ недействителен, так как он ожидает чего-то еще).

  • Чтобы проверить первый случай, убедитесь, что все параметры сначала заданы для строки
  • Чтобы проверить второй случай, создайте свой SoapClient с параметром trace, установленным в true, чтобы получить доступ к фактическому XML-ответу с сервера через $ client -> __ getLastResponse () после этого (вы можете использовать это для отладки запроса также через __getLastRequest ( )).

Некоторые дополнительные замечания / вопросы:

  • Согласно опубликованному WSDL, «CanLoadProductRequest» имеет пятый параметр «esn», который вы не предоставляете в своем вызове функции.
  • Любая причина, по которой вы используете $client->__soapCall(«CanLoadProduct», $params) вместо $client->CanLoadProduct($username, $password, etc.) ? (Первая версия представляет собой вариант более низкого уровня, который предназначен для использования в сценариях, отличных от non_WSDL. Вторая версия может дать вам более подробную ошибку / исключение)
  • Можете ли вы протестировать вызов SOAP на CanLoadProductRequest другими способами? Ошибка может быть на стороне сервера, пытаясь вернуть тип результата, который не соответствует определению WSDL.

У меня такая же проблема.

В настройках soapUI я проверил параметр «Настройки» → «Параметры редактора» → «Проверить ответы», и я получил эту информацию:

строка 3027: Недопустимое десятичное значение: неожиданный символ ’44’.

Это решило мою проблему. Поле содержит неправильное значение типа.

У меня была такая же проблема при попытке передать XML в качестве параметра в один из моих веб-сервисов. Обтекание XML-данных в избавилось от SOAP-ERROR: Кодирование: нарушение правил кодирования и все работало нормально.

Другие детали:
1. Параметр был также определен как xsd: string.
2. WSDL был документом / буквальным.
3. Использование встроенного SOAP-класса с php 5.2.10.

У меня была та же проблема, и я решил использовать этот синтаксис для __soapCall :

Я получал эту ошибку с помощью инструмента SoapUI, пока я не отформатировал ответ с помощью реальных данных теста, а не только. Также с SoapUI ответ может быть более чем ожидаемым и, возможно, придется сократить ожидаемый ответ, удалив несколько необязательных параметров ответа. Надеюсь это поможет?

Там также есть своего рода ошибка на PHP, где неправильный тип не оставляет места для возврата правильного SOAP-файла обратно клиенту.

У меня была та же проблема, и мне удалось исправить ее, исправив WSDL, который предполагал, что сервер отправит целое число для определенного значения, но фактически отправил строку. Возможно, изменение WSDL:

Источник

SOAP-ERROR: Кодирование: Нарушение правил кодирования?

Ребята, я застрял, бьюсь головой о стол последние несколько часов.

Я пытаюсь использовать службу, и у меня есть 8 других функций, которые я вызываю, которые почти ИДЕНТИЧНЫ по своей природе для этой, но эта приводит к ошибке «SOAP-ERROR: Encoding: нарушение правил кодирования».

Вот вызов функции (wsdl опущен в целях безопасности):

Итак, эта функция подключается к веб-сервису, обязательными элементами являются: имя пользователя, пароль, prod, mdn, все 4 из которых я предоставляю как часть массива $ params. Имя пользователя / пароль определены ранее и работают нормально, поскольку остальные 8 функций используют веб-службу без каких-либо проблем.

Массив $ data [] (который я передаю функции) содержит: $ data [‘productid’] $ data [‘mdn’] больше ничего не используется.

по какой-то необъяснимой причине, и поиск в Google этой ошибки ни к чему не приведет. Кто-нибудь еще сталкивался с этим? Запуск PHP 5.2.9-2. Странно то, что это идентично этой функции, которая работает на 100%:

Вот WSDL (он должен был быть опубликован первым):

Если бы это был клиент .NET, я бы попытался жестко запрограммировать «prod» и «mdn», чтобы они были заведомо правильными значениями, и посмотрел бы, что произойдет. Если это сработает, я бы удалил жесткие коды по одному, чтобы увидеть, в чем проблема. Затем я смотрел на неудачное значение, чтобы увидеть, есть ли в нем что-нибудь особенное. — John Saunders

Это была моя первая мысль. — Rob Drimmie

Я пробовал его жестко кодировать, но результат тот же, ОЧЕНЬ странный. Я не знаю ни о каком другом методе устранения этой неисправности. — Jakub

Интересный. Я думаю, что следующее, что я хотел бы сделать, это взглянуть на WSDL, и следующее после этого — попытаться создать подобный клиент, используя другой язык, например Java или C #. Фактически, при всем уважении к «скриптовым» языкам, я бы удостоверился, что другой язык был языком с большей поддержкой инструментов и т. Д. Я бы попытался реализовать только один вызов. Было бы интересно посмотреть, сработает ли это. — John Saunders

Я включил WSDL, извините, что должен был сделать это раньше. — Jakub

11 ответы

Похоже, у вас где-то есть несоответствие типов, либо при сборке вашего запроса (один из параметров не является строкой типа), либо сервер возвращает что-то, кроме int (нарушая определение ответа WSDL и, таким образом, заставляя клиента учитывать ответ недействителен, так как он ожидает чего-то другого).

  • Чтобы проверить первый случай, убедитесь, что сначала все параметры передаются в строку
  • Чтобы проверить второй случай, создайте свой SoapClient с прослеживать для параметра установлено значение true, чтобы впоследствии получить доступ к фактическому ответу XML от сервера через $ client -> __ getLastResponse () (вы можете использовать это для отладки запроса также через __getLastRequest ()).

Некоторые дополнительные наблюдения / вопросы:

  • Согласно опубликованному WSDL, CanLoadProductRequest имеет пятый параметр esn, который вы не указываете в вызове функции.
  • Любая причина, по которой вы используете $client->__soapCall(«CanLoadProduct», $params) вместо $client->CanLoadProduct($username, $password, etc.) ? (Первая версия представляет собой вариант более низкого уровня, который предназначен для использования в сценариях, отличных от WSDL. Вторая версия может дать вам более подробную информацию об ошибке / исключении)
  • Можете ли вы протестировать SOAP-вызов CanLoadProductRequest каким-либо другим способом? Ошибка могла быть на стороне сервера, пытаясь вернуть тип результата, который не соответствует определению WSDL.

ответ дан 22 авг.

‘Esn’ не является обязательным, и этот шаблон данных user / pass / prod / mdn / esn является стандартным для большинства других 8 вызовов, которые я использую, ни один из них, похоже, не завершился неудачно, кроме этого. Я пробовал $ client-> CanLoadProduct ($ params), но это привело к: Уведомление о преобразовании массива в строку из PHP — Якуб

Упс — извините, если вы используете нотацию $ client-> CanLoadProduct (), вы передаете не массив параметров, а отдельные параметры, как при стандартном вызове функции (например, $ client-> CanLoadProduct ($ username, $ пароль и тд))) — Хенрик Опель

Еще одна вещь, которую стоит попробовать, — это явное преобразование параметров в строку перед вызовом (например, productid может быть здесь передано как int) — Хенрик Опель

Отредактированный ответ в соответствии с новыми предположениями, взятыми из комментариев. — Хенрик Опель

Я пометил это как ответ, потому что это помогло мне отметить все возможные проблемы. Я пришел к выводу, что WSDL вызывал ошибку, поскольку это такой простой вызов SOAP, и в итоге я не использовал его, поскольку это был вызов проверки, и функция проверки после отправки вернула бы сообщение об ошибке, если оно не прошло, через который также работал как чек. Я поднял этот вопрос с дизайнером API. Спасибо за вашу помощь всем! — Якуб

У меня была такая же проблема.

В настройках soapUI я проверил опцию Preferences → Editor Settings → Validate Responses и получил следующую информацию:

строка 3027: недопустимое десятичное значение: неожиданный символ ’44’.

Это решило мою проблему. Поле содержит неверное значение типа.

Источник

SOAP-ERROR: Кодировка: Нарушение правил кодирования?

Я пытаюсь использовать службу, и у меня есть еще 8 других функций, которые я называю почти идентичными по своему характеру, но это приводит к ошибке «Ошибка SOAP-ERROR: кодирование: нарушение правил кодирования».

Вот вызов функции (wsdl пропущен для безопасности):

Итак, эта функция, подключается к веб-сервису, требуемые элементы: имя пользователя, пароль, prod, mdn, все 4 из которых я поставляю как часть массива $params. Имя пользователя/пароль определены ранее и работают нормально, так как остальные 8 функций не требуют веб-службы без проблем.

Массив $data [] (который я передаю функции) содержит: $ данных [ ‘ProductID’] $ данных [ ‘MDN’] ничего не используется.

по какой-то необъяснимой причине, и Googling эта ошибка не дает мне ниоткуда. Кто-нибудь еще сталкивается с этим? Запуск PHP 5.2.9-2. Странно, что это идентично этой функции, которая работает на 100%:

Вот WSDL (должен был опубликовать это в первую очередь):

9 ответов

Похоже, что у вас есть несоответствие типов где-то, либо при сборке вашего запроса (один из параметров не из строки типа), либо сервер возвращает что-то иное, чем int (нарушая определение ответа WSDL и тем самым вызывая его считать ответ недействительным, поскольку он ожидает чего-то еще).

  • Чтобы проверить первый случай, убедитесь, что все параметры сначала заданы в строке
  • Чтобы проверить второй случай, создайте свой SoapClient с параметром trace, установленным в true, чтобы получить доступ к фактическому XML-ответу с сервера через $client → __ getLastResponse() после этого (вы можете использовать это для отладки запроса также через __getLastRequest()).

Некоторые дополнительные замечания/вопросы:

  • Согласно опубликованному WSDL, «CanLoadProductRequest» имеет пятый параметр «esn», который вы не предоставляете в своем вызове функции.
  • Любая причина, по которой вы используете $client->__soapCall(«CanLoadProduct», $params) вместо $client->CanLoadProduct($username, $password, etc.) ? (Первая версия представляет собой вариант более низкого уровня, который предназначен для использования в сценариях, отличных от _WSDL. Вторая версия может дать вам более подробную ошибку/исключение)
  • Можете ли вы протестировать SOAP-вызов на CanLoadProductRequest другими способами? Ошибка может быть на стороне сервера, пытаясь вернуть тип результата, который не соответствует определению WSDL.

Источник

SOAP Error #393

Microsoft Exchange version: 2010 SP2

Description of problem:
Collecting all unread mails of a special folder.
When running in web, all things are fine, when running in cron i got the following error:

SOAP-ERROR: Encoding: Violation of encoding rules in [. ]/ews/php-ews/ExchangeWebServices.php

Example request:
Web-Request

when cron is calling script request is:

Cant see any differences, so why i get this error when collecting mails.

The text was updated successfully, but these errors were encountered:

In the future, please format your code using Markdown code blocks: https://guides.github.com/features/mastering-markdown/

I see that you are using an old version of this library which is not supported. Upgrading to the latest beta may resolve your issue, as many bugs have addressed.

Thanks, so i changed up to version 1, and i had the same error.

PHP Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules in
vendor/php-ews/php-ews/src/Client.php on line 1631

The fact that this works via web and not cli points to an environmental issue. I would recommend looking at the difference between your configurations of each. In particular, if you’re using PHP getClient(); $request_xml = $soap->__getLastRequest(); $response_xml = $soap->__getLastResponse(); >»>

After Update from PHP 7.2 to PHP 7.4 I get the same Error (before it worked):

PHP Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules in vendor/php-ews/php-ews/src/Client.php on line 1631

Not on UpdateItem() call but on FindItem()

So i used your code for debugging the xml:

My IDE is marking the «value=» and «id=» as Error as it expects upper case «Value=» and «Id=» matching the Class Members — but i dont know if this is connected to the error.

Источник

Ребята, я застрял, ударив головой из-за стола в течение последних нескольких часов.

Я пытаюсь использовать службу, и у меня есть еще 8 других функций, которые я называю почти идентичными по своему характеру, но это приводит к ошибке «Ошибка SOAP-ERROR: кодирование: нарушение правил кодирования».

  • Отправка XML-файла через удаленный URL-адрес PHP
  • Вызов неопределенного метода DOMDocument :: getElementsByClassName ()
  • как преобразовать xml-массив в php-массив
  • Как добавить и изменить теги XML в PHP
  • Сохранить страницу как XML

Heres вызов функции (wsdl пропущен для обеспечения безопасности):

function CanLoadProduct($data){ $client = new SoapClient('wsdl-url'); $params = array('username' => $this->username, 'password' => $this->password, 'prod' => $data['productid'], 'mdn' => $data['mdn']); try { $reply = $client->__soapCall("CanLoadProduct", $params); } catch (Exception $e) { echo 'Error: ', $e->getMessage(), "n"; print_r($params); die(); } if( $reply['result'] == 1 ){ return TRUE; // 1 = true } else { return FALSE; } } 

Итак, эта функция, подключается к веб-сервису, необходимыми элементами являются: имя пользователя, пароль, prod, mdn, все 4 из которых я поставляю как часть массива $ params. Имя пользователя / пароль определены раньше и работают нормально, так как остальные 8 функций без проблем обрабатывают веб-службу.

Массив $ data [] (который я передаю функции) содержит: $ data [‘productid’] $ data [‘mdn’] ничего не используется.

я осознаю

 SOAP-ERROR: Encoding: Violation of encoding rules 

по какой-то необъяснимой причине, и Гуглинг эта ошибка не дает мне нигде. Кто-нибудь еще сталкивается с этим? Запуск PHP 5.2.9-2. Странно то, что эта функция идентична этой функции, которая работает на 100%:

  function GetPIN($productid){ $client = new SoapClient('wsdl-url'); $params = array('username' => $this->username, 'password' => $this->password, 'prod' => $productid); try { $reply = $client->__soapCall("GetPIN", $params); } catch (Exception $e) { echo 'Error: ', $e->getMessage(), "n"; die(); } return $reply; } 

Вот WSDL (должен был опубликовать это в первую очередь):

 <?xml version="1.0" encoding="ISO-8859-1"?> <definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="ready:test" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="ready:test"> <types> <xsd:schema targetNamespace="ready:test" > <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" /> <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" /> </xsd:schema> </types> <message name="CanLoadProductRequest"> <part name="username" type="xsd:string" /> <part name="password" type="xsd:string" /> <part name="prod" type="xsd:string" /> <part name="mdn" type="xsd:string" /> <part name="esn" type="xsd:string" /></message> <message name="CanLoadProductResponse"> <part name="result" type="xsd:int" /></message> <portType name="CanLoadProductPortType"> <operation name="CanLoadProduct"> <input message="tns:CanLoadProductRequest"/> <output message="tns:CanLoadProductResponse"/> </operation> </portType> <binding name="CanLoadProductBinding" type="tns:CanLoadProductPortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="CanLoadProduct"> <soap:operation soapAction="{url-removed}" style="rpc"/> <input> <soap:body use="encoded" namespace="" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <service name="CanLoadProduct"> <port name="CanLoadProductPort" binding="tns:CanLoadProductBinding"> <soap:address location="{url-removed}"/> </port> </service> </definitions> 
  • DOMDocument :: loadXML и HTML-объекты
  • Как решить «вызов неопределенной функции domxml_new_doc () …»
  • Форматирование ответов PHP Soap Server
  • Как изменить имена тегов XML с помощью PHP?
  • Проверка PageRank через XML

Похоже, что у вас есть несоответствие типа где-то, либо при сборке вашего запроса (один из параметров не относится к строке типа), либо сервер возвращает что-то иное, чем int (нарушая определение ответа WSDL и тем самым заставляя клиента рассматривать ответ недействителен, так как он ожидает чего-то еще).

  • Чтобы проверить первый случай, убедитесь, что все параметры сначала заданы для строки
  • Чтобы проверить второй случай, создайте свой SoapClient с параметром trace, установленным в true, чтобы получить доступ к фактическому XML-ответу с сервера через $ client -> __ getLastResponse () после этого (вы можете использовать это для отладки запроса также через __getLastRequest ( )).

Некоторые дополнительные замечания / вопросы:

  • Согласно опубликованному WSDL, «CanLoadProductRequest» имеет пятый параметр «esn», который вы не предоставляете в своем вызове функции.
  • Любая причина, по которой вы используете $client->__soapCall("CanLoadProduct", $params) вместо $client->CanLoadProduct($username, $password, etc.) ? (Первая версия представляет собой вариант более низкого уровня, который предназначен для использования в сценариях, отличных от non_WSDL. Вторая версия может дать вам более подробную ошибку / исключение)
  • Можете ли вы протестировать вызов SOAP на CanLoadProductRequest другими способами? Ошибка может быть на стороне сервера, пытаясь вернуть тип результата, который не соответствует определению WSDL.

У меня такая же проблема.

В настройках soapUI я проверил параметр «Настройки» → «Параметры редактора» → «Проверить ответы», и я получил эту информацию:

строка 3027: Недопустимое десятичное значение: неожиданный символ ’44’.

Это решило мою проблему. Поле содержит неправильное значение типа.

У меня была такая же проблема при попытке передать XML в качестве параметра в один из моих веб-сервисов. Обтекание XML-данных в <![CDATA[ ... ]]> избавилось от SOAP-ERROR: Кодирование: нарушение правил кодирования и все работало нормально.

Другие детали:
1. Параметр был также определен как xsd: string.
2. WSDL был документом / буквальным.
3. Использование встроенного SOAP-класса с php 5.2.10.

У меня была та же проблема, и я решил использовать этот синтаксис для __soapCall :

 ... $params = new SoapParam($data, 'parameters'); $response = $this->__soapCall('methodName', array(new SoapVar($data, XSD_ANYTYPE, 'parameters')) ); ... 

Вместо

 __soapCall('methodName', array($params) 

Я получал эту ошибку с помощью инструмента SoapUI, пока я не отформатировал ответ с помощью реальных данных теста, а не только??. Также с SoapUI ответ может быть более чем ожидаемым и, возможно, придется сократить ожидаемый ответ, удалив несколько необязательных параметров ответа. Надеюсь это поможет?

 <![CDATA[<?xml version="1.0" encoding="utf-8"?> <CONTENTXML></CONTENTXML]]></xmlCallString>]]> 

У меня была эта проблема в PhpStorm при выполнении модульных тестов. Я отключил кеш wsdl и работал: ini_set («soap.wsdl_cache_enabled», «0»);

  • #1

SOAP-ERROR: Encoding: Violation of encoding rules

Приветствую.
Имеется проблема с использванием SOAP extension. Есть агент у Lotus сервера, который работает как soap сервер.
Вот тут его wsdl.
С ним из php с использованием класса SoapClient (из экстеншна) нормально работается за исключением случаев, когда вызывается CURRENTUSERTASKS(). (см. wsdl).
В этом случае скрипт валится с Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules. Если использовать NuSoap клиент, все отрабатывает нормально.
Кто-нибудь сталкивался?
———————————
PHP 5.2.1, FreeBSD 5.4-RELEASE-p8, Apache/2.2.4

  • #2

В SOAP extension проблемы с символами, которые лежат за пределами ASCII.

  • #3

хм. ну ok, попробую выяснить, в этом ли проблема в моем случае, спасибо.

  • #4

ну ok, попробую выяснить, в этом ли проблема в моем случае

Mephistophelну и отправь сообщение без символа… и с символом… или сделай замену…

Ну и потомкам хотелось бы народу услышать результаты твоих изысканий, а то тема была а результата нет

  • #5

Автор оригинала: Alexandre
Ну и потомкам хотелось бы народу услышать результаты твоих изысканий, а то тема была а результата нет.

Пришлось на время отложить эту штуку. Планирую еще вечером поколупаться. Как только у меня будет удобоваримое объяснение, я отпишу, чтобы тема без результата не осталась.

-~{}~ 04.04.07 14:35:

В общем, так, проблема нашлась. И заключается она в том, что в тип double у лотуса разделителем является ЗАПЯТАЯ.
Смотрим, как парсятся типы в soap extension: soap_encoding.c Смотрим там, как работает to_zval_double():

Код:

switch (is_numeric_string((char*)data->children->content, strlen((char*)data->children->content), &lval, &dval, 0)) {
	case IS_LONG:
		Z_TYPE_P(ret) = IS_DOUBLE;
		Z_DVAL_P(ret) = lval;
		break;
	case IS_DOUBLE:
		Z_TYPE_P(ret) = IS_DOUBLE;
		Z_DVAL_P(ret) = dval;
		break;
	default:
		soap_error0(E_ERROR, "Encoding: Violation of encoding rules");
}

Вот где генерится наш фатал. Смотрим, как работает is_numeric_string():
zend_operators.h
и видим, что запятая в качестве разделителя для double использоваться не может.

Собственно, в исходники php можно было и не лезть, но уж больно досадная проблема была.

Answer by Astrid Ware

I solved the problem (SOAP-ERROR: Encoding: Violation of encoding rules) by changing the PHP version from 7.2 to 7.3,I am trying to consume a service, and I have 8 other functions that I call that are almost IDENTICAL in nature to this one, but this one, results in a ‘SOAP-ERROR: Encoding: Violation of encoding rules’ error.,May solve your issue, here is some information on the particular case I was facing: https://blog.dotnetframework.org/2016/12/06/uncaught-soapfault-exception-sender-soap-error-encoding-violation-of-encoding-rules/,I had the same problem when trying to pass XML as a parameter to one of my webservices. Wrapping the XML data in <![CDATA[ … ]]> got rid of the SOAP-ERROR: Encoding: Violation of encoding rules and everything worked fine.

Other details:
1. The parameter was defined as xsd:string as well.
2. WSDL was document/literal.
3. Using built in SOAP class with php 5.2.10.

<![CDATA[<?xml version="1.0"
encoding="utf-8"?>
<CONTENTXML></CONTENTXML]]></xmlCallString>]]>

Answer by Paityn McCormick

I generated a package to connect to an OTA web service (Opentravel.org), but I keep getting this «violation of encoding rules» error. I can’t seem to figure out what I’m doing wrong.,But instead I’m getting this:,Also the generated package is here https://github.com/ammonkc/ota-ehi,

The text was updated successfully, but these errors were encountered:

<OTA_VehLocDetailRQ TimeStamp="2011-01-10T09:30:00" Target="Production" Version="3.0" TransactionIdentifier="100000001" SequenceNmbr="1" xmlns="http://www.opentravel.org/OTA/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 file:///C:/Users/Documents/XML/2012b%20Updated/OTA_VehLocDetailRQ.xsd">
	<POS>
		<Source>
			<RequestorID Type="4" ID="XMLRTA">
				<CompanyName Code="EX" CompanyShortName="EHIXMLTEST"/>
			</RequestorID>
		</Source>
		<Source>
			<RequestorID Type="4" ID="00000000" ID_Context="IATA"/>
		</Source>
	</POS>
	<Location LocationCode="STL71"/>
	<Date PickUpDateTime="2016-03-09T10:00:00" ReturnDateTime="2016-03-10T10:00:00"/>
	<Vendor Code="AL"/>
	<TPA_Extensions>
		<TPA_Extension_Flags OpScheduleIndicator="true"/>
	</TPA_Extensions>
</OTA_VehLocDetailRQ>

Answer by Musa Marquez

Heres the function call (wsdl omitted for security):,I am trying to consume a service, and I have 8 other functions that I call that are almost IDENTICAL in nature to this one, but this one, results in a ‘SOAP-ERROR: Encoding: Violation of encoding rules’ error.,To test the first case, ensure casting all parameters to string first,I have a soap function called get_file_list that I would like to write for PHP however I can not get it to work. It has three parameters, 1) start time, 2) end…

Heres the function call (wsdl omitted for security):

    function CanLoadProduct($data){

    $client = new SoapClient('wsdl-url');

    $params = array('username'   => $this->username,
                    'password'  => $this->password,
                    'prod'      => $data['productid'],
                    'mdn'       => $data['mdn']);

    try {
        $reply = $client->__soapCall("CanLoadProduct", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        print_r($params);
        die();
    }

    if( $reply['result'] == 1 ){
        return TRUE;        // 1 = true
    } else {
        return FALSE;
    }

}

I am getting

SOAP-ERROR: Encoding: Violation of encoding rules

for some unexplained reason, and Googling this error gets me nowhere. Anyone else run into this? Running PHP 5.2.9-2. The strange thing is this is identical to this function which works 100%:

    function GetPIN($productid){

    $client = new SoapClient('wsdl-url');

    $params = array('username'  => $this->username,
                    'password'  => $this->password,
                    'prod'      => $productid);

    try {
        $reply = $client->__soapCall("GetPIN", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        die();
    }
        return $reply;
}

Here is the WSDL (should have posted this first):

<?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" 
    xmlns:tns="ready:test" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
    xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="ready:test">
<types>
<xsd:schema targetNamespace="ready:test"
>
 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
</xsd:schema>
</types>
<message name="CanLoadProductRequest">
  <part name="username" type="xsd:string" />
  <part name="password" type="xsd:string" />
  <part name="prod" type="xsd:string" />    
  <part name="mdn" type="xsd:string" />
  <part name="esn" type="xsd:string" /></message>
<message name="CanLoadProductResponse">
  <part name="result" type="xsd:int" /></message>
<portType name="CanLoadProductPortType">
  <operation name="CanLoadProduct">
    <input message="tns:CanLoadProductRequest"/>
    <output message="tns:CanLoadProductResponse"/>
  </operation>
</portType>

<binding name="CanLoadProductBinding" type="tns:CanLoadProductPortType">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
  <operation name="CanLoadProduct">
    <soap:operation soapAction="{url-removed}"/>
    <input>
        <soap:body use="encoded" namespace="" 
           encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </input>
    <output>
        <soap:body use="encoded" namespace="" 
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </output>
  </operation>
</binding>
<service name="CanLoadProduct">
  <port name="CanLoadProductPort" binding="tns:CanLoadProductBinding">

    <soap:address location="{url-removed}"/>
  </port>
</service>
</definitions>

Answer by Armando Villa

It is possible that the SOAP request is incorrectly formatted. I’ve been using SoapUI and by default all the parameters are set to ‘?’ initially, if you make this request PHP will fail and respond with the error message you have reported. You cannot catch this, because no exception is thrown, this is because it is a fatal error.,If you add any files,it will delete all existing files related to this question-(questions only answer remains unchanged),I am trying to use Yii to provide a web service. The auto-generated wsdl is below. I can successfully consume the web service from the command line, but through a web browser, I get ,If you add any files,it will delete all existing files related to this answer-(only this answer)

I am trying to use Yii to provide a web service. The auto-generated wsdl is below. I can successfully consume the web service from the command line, but through a web browser, I get

SOAP-ERROR: Encoding: Violation of encoding rules

I am new to SOAP, so I am not sure how to debug the problem. Here is the PHP code I am using to consume the web service:

<?php
    $client=new SoapClient('{url omitted for security}',
        array('trace'=>1,'exceptions'=>1));
    try {
        $result = $client->getPerson(90043412);
        var_dump($result);
    } catch (SoapFault $fault) {
        echo $fault->getMessage() . '<br />';
        echo 'REQUEST <br />';
        echo '<pre>';
        echo $client->__getLastRequestHeaders();
        echo $client->__getLastRequest();
        echo '</pre>';
        echo 'RESPONSE <br />';
        echo '<pre>';
        echo $client->__getLastResponseHeaders();
        echo $client->__getLastResponse();
        echo '</pre>';
        echo 'TRACE <br />';
        echo '<pre>';
        var_dump($fault->getTrace());
        echo '</pre>';
    }
?>

Answer by Byron Barry

我正在尝试使用 PHP 连接到 SOAP API,但不断收到以下错误:,关于php — fatal error : SOAP-ERROR: Encoding: Violation of encoding rules in PHP,我们在Stack Overflow上找到一个类似的问题:

https://stackoverflow.com/questions/37815419/

我正在尝试使用 PHP 连接到 SOAP API,但不断收到以下错误:

Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="http://localhost/">
   <soapenv:Header/>
   <soapenv:Body>
      <loc:ws_customer_info soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <customerpacket xsi:type="loc:LoyaltySchemecustomerpacket">
            <auth_id xsi:type="xsd:string">auth-code-here</auth_id>
            <customerid xsi:type="xsd:string">0</customerid>
            <customer_email xsi:type="xsd:string">[email protected]</customer_email>
         </customerpacket>
      </loc:ws_customer_info>
   </soapenv:Body>
</soapenv:Envelope>

<?php
$context = stream_context_create([
    'http'=> [
        'user_agent' => 'PHPSoapClient'
    ]
]);

$accent = new SoapClient( 'http://domain.com/loyaltyserver.php?wsdl', [
    'stream_context' => $context,
    'cache_wsdl' => WSDL_CACHE_NONE,
    'trace' => true
]);

$data = [
    'auth_id' => (string) 'my-auth-code',
    'customer_email' => (string) '[email protected]',
    'customerid' => (string) 0
];

$result = $accent->ws_customer_info($data);

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://localhost/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
    <ns1:ws_customer_info>
        <customerpacket xsi:type="ns1:LoyaltySchemecustomerpacket">
            <auth_id xsi:type="xsd:string">my-auth-code</auth_id>
            <customerid xsi:type="xsd:string">0</customerid>
            <customer_email xsi:type="xsd:string">[email protected]</customer_email>
        </customerpacket>
    </ns1:ws_customer_info>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Answer by Anais Reyna

I am trying to use the service and I have 8 other functions that I call almost identical in nature, but this leads to the error «Error SOAP-ERROR: encoding: violation of encoding rules».,I had the same problem when trying to pass XML as a parameter to one of my web services. Wrapping XML data in <![CDATA[ … ]]> got rid of SOAP-ERROR: Encoding: violation of encoding rules and everything worked fine.Other details:1. The parameter was also defined as xsd: string.2. WSDL was a document / literal.3. Using the built-in SOAP class with php 5.2.10.,May solve your problem, here is some information about a specific case that I came across: https://blog.dotnetframework.org/2016/12/06/uncaught-soapfault-exception-sender-soap-error-encoding-violation-of -encoding-rules /,There is also an error in PHP where the wrong type leaves no room for returning the correct SOAP file back to the client.

Here is the function call (wsdl skipped for security):

function CanLoadProduct($data){ $client = new SoapClient('wsdl-url'); $params = array('username' => $this->username, 'password' => $this->password, 'prod' => $data['productid'], 'mdn' => $data['mdn']); try { $reply = $client->__soapCall("CanLoadProduct", $params); } catch (Exception $e) { echo 'Error: ', $e->getMessage(), "n"; print_r($params); die(); } if( $reply['result'] == 1 ){ return TRUE; // 1 = true } else { return FALSE; } } 

I get

 SOAP-ERROR: Encoding: Violation of encoding rules 

for some inexplicable reason, and Googling this error does not give me anywhere. Anyone else run into this? Running PHP 5.2.9-2. It is strange that this is identical to this function, which works 100%:

  function GetPIN($productid){ $client = new SoapClient('wsdl-url'); $params = array('username' => $this->username, 'password' => $this->password, 'prod' => $productid); try { $reply = $client->__soapCall("GetPIN", $params); } catch (Exception $e) { echo 'Error: ', $e->getMessage(), "n"; die(); } return $reply; } 

Here is the WSDL (was supposed to publish this first):

 <?xml version="1.0" encoding="ISO-8859-1"?> <definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="ready:test" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="ready:test"> <types> <xsd:schema targetNamespace="ready:test" > <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" /> <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" /> </xsd:schema> </types> <message name="CanLoadProductRequest"> <part name="username" type="xsd:string" /> <part name="password" type="xsd:string" /> <part name="prod" type="xsd:string" /> <part name="mdn" type="xsd:string" /> <part name="esn" type="xsd:string" /></message> <message name="CanLoadProductResponse"> <part name="result" type="xsd:int" /></message> <portType name="CanLoadProductPortType"> <operation name="CanLoadProduct"> <input message="tns:CanLoadProductRequest"/> <output message="tns:CanLoadProductResponse"/> </operation> </portType> <binding name="CanLoadProductBinding" type="tns:CanLoadProductPortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="CanLoadProduct"> <soap:operation soapAction="{url-removed}" style="rpc"/> <input> <soap:body use="encoded" namespace="" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output> <soap:body use="encoded" namespace="" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <service name="CanLoadProduct"> <port name="CanLoadProductPort" binding="tns:CanLoadProductBinding"> <soap:address location="{url-removed}"/> </port> </service> </definitions> 

Answer by Lincoln Giles

Using — Prizm 3.1 Patch 7 / PHP 5.2.6Hi everyone,We are getting random SOAP errors with Prizm. The script will be workingjust fine searching / editing elements… and then we get this error:

Using — Prizm 3.1 Patch 7 / PHP 5.2.6

Hi everyone,

We are getting random SOAP errors with Prizm. The script will be working
just fine searching / editing elements… and then we get this error:

<b>Fatal error</b>:  Uncaught SoapFault exception: [Client] SOAP-ERROR: Encoding: Violation of encoding rules in /site/sections/wireless/ips/prizm/tree.php:39Stack trace:#0 [internal function]: SoapClient->__call(‘getPrizmElement…’, Array)#1 /site/sections/wireless/ips/prizm/tree.php(39): SoapClient->getPrizmElements(‘Network.ID’, ‘6’, ‘=’)#2 /site/read.php(148): require_once(’/home/websites/…’)#3 {main}  thrown in <b>/site/sections/wireless/ips/prizm/tree.php</b> on line <b>39</b>

Bug #47719 SOAP-ERROR: Encoding: Violation of encoding rules
Submitted: 2009-03-19 16:04 UTC Modified: 2013-02-18 00:33 UTC
Votes: 5
Avg. Score: 4.8 ± 0.4
Reproduced: 5 of 5 (100.0%)
Same Version: 2 (40.0%)
Same OS: 0 (0.0%)
From: oxomichael at hotmail dot com Assigned:
Status: No Feedback Package: SOAP related
PHP Version: 5.2.9 OS: Windows
Private report: No CVE-ID: None

 [2009-03-19 16:04 UTC] oxomichael at hotmail dot com

Description:
------------
I get an SOAP Error violation encoding 

From Windows XP with WAMPSERVER PHP5.2.9-r1
From Ubuntu 8.10 & PHP 5.2.6

From Gentoo & PHP 5.2.8 (I have the error but i have the return from webservice with LastResponse)


Works Fine on Ubunutu 8.0.4 LTS & PHP 5.2.4 (Production server)

The webservice i request wait for an string compose as "xml" et send also a string as xml (see code example for what i send)

Soap request :
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://webservices.infogreffe.fr/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:getProduitsWebServicesXML><param0 xsi:type="xsd:string">&lt;demande&gt;&lt;emetteur&gt;&lt;code_abonne&gt;85000109&lt;/code_abonne&gt;&lt;mot_passe&gt;166&lt;/mot_passe&gt;&lt;reference_client&gt;G0&lt;/reference_client&gt;&lt;code_requete&gt;&lt;type_profil&gt;A&lt;/type_profil&gt;&lt;origine_emetteur&gt;IC&lt;/origine_emetteur&gt;&lt;nature_requete&gt;C&lt;/nature_requete&gt;&lt;type_document&gt;AC&lt;/type_document&gt;&lt;type_requete&gt;S&lt;/type_requete&gt;&lt;media&gt;WS&lt;/media&gt;&lt;mode_diffusion&gt;&lt;mode type="XL"/&gt;&lt;mode type="T"/&gt;&lt;mode type="C"/&gt;&lt;/mode_diffusion&gt;&lt;/code_requete&gt;&lt;/emetteur&gt;&lt;commande&gt;&lt;num_siren&gt;494967938&lt;/num_siren&gt;&lt;/commande&gt;&lt;/demande&gt;</param0></ns1:getProduitsWebServicesXML></SOAP-ENV:Body></SOAP-ENV:Envelope>


Reproduce code:
---------------
Code give as information because i can't have any debug information from webservice.

Code URL : http://oxomichael.serveftp.net/michael/infogreffe.txt



Expected result:
----------------
<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><SOAP-ENV:Body><ns0:getProduitsWebServicesXMLResponse xmlns:ns0='urn:local' SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'><return xsi:type='xsd:string'><liste_depot_acte><depot_acte><num_gest><greffe>7803</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>04241</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>17380</num_depot><date_depot>2008-12-03</date_depot><acte><date_acte>2008-11-24</date_acte><num_acte>01</num_acte><type_acte>PG</type_acte><type_acte_libelle>PROCES VERBAL D'ASSEMBLEE GENERALE ORDINAIRE</type_acte_libelle><nbpages_acte>3</nbpages_acte><decision><nature>CHANGEMENT DE COMMISSAIRES AUX COMPTES TITULAIRE ET SUPPLEANT</nature><libelle></libelle></decision><mode_diffusion><mode type="C"></mode><mode type="T"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>7501</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>01601</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>86746</num_depot><date_depot>2008-09-26</date_depot><acte><date_acte>2008-09-25</date_acte><num_acte>01</num_acte><type_acte>RA</type_acte><type_acte_libelle>RAPPORT</type_acte_libelle><nbpages_acte>6</nbpages_acte><decision><nature></nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>9401</greffe><dossier_millesime>07</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>01328</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>4476</num_depot><date_depot>2007-03-21</date_depot><acte><date_acte>2007-02-19</date_acte><num_acte>01</num_acte><type_acte>04</type_acte><type_acte_libelle>STATUTS CONSTITUTIFS</type_acte_libelle><nbpages_acte>16</nbpages_acte><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-02-19</date_acte><num_acte>02</num_acte><type_acte>AA</type_acte><type_acte_libelle>ACTE</type_acte_libelle><nbpages_acte>1</nbpages_acte><decision><nature>NOMINATION DE DIRECTEUR GENERAL</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-02-27</date_acte><num_acte>03</num_acte><type_acte>AA</type_acte><type_acte_libelle>ACTE</type_acte_libelle><nbpages_acte>1</nbpages_acte><decision><nature>ATTESTATION BANCAIRE</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-02-27</date_acte><num_acte>04</num_acte><type_acte>AA</type_acte><type_acte_libelle>ACTE</type_acte_libelle><nbpages_acte>1</nbpages_acte><decision><nature>LISTE DES SOUSCRIPTEURS</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>7501</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>01601</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>86904</num_depot><date_depot>2008-09-26</date_depot><acte><date_acte>2008-09-24</date_acte><num_acte>01</num_acte><type_acte>PH</type_acte><type_acte_libelle>PROCES VERBAL D'ASSEMBLEE MIXTE</type_acte_libelle><nbpages_acte>5</nbpages_acte><decision><nature>CHANGEMENT DE DATE D'EXERCICE SOCIAL</nature><libelle>AU 31/12</libelle></decision><decision><nature>MODIFICATION(S) STATUTAIRE(S)</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2008-09-24</date_acte><num_acte>02</num_acte><type_acte>06</type_acte><type_acte_libelle>STATUTS A JOUR</type_acte_libelle><nbpages_acte>17</nbpages_acte><decision><nature></nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>7501</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>01601</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>6338</num_depot><date_depot>2008-01-23</date_depot><acte><date_acte>2007-11-16</date_acte><num_acte>01</num_acte><type_acte>09</type_acte><type_acte_libelle>STATUTS APRES TRANSFERT DE SIEGE</type_acte_libelle><nbpages_acte></nbpages_acte><decision><nature></nature><libelle></libelle></decision><mode_diffusion><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-11-16</date_acte><num_acte>02</num_acte><type_acte>PA</type_acte><type_acte_libelle>PROCES VERBAL</type_acte_libelle><nbpages_acte>6</nbpages_acte><decision><nature>AUGMENTATION DE CAPITAL</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-11-15</date_acte><num_acte>03</num_acte><type_acte>PA</type_acte><type_acte_libelle>PROCES VERBAL</type_acte_libelle><nbpages_acte>6</nbpages_acte><decision><nature>AUGMENTATION DE CAPITAL</nature><libelle></libelle></decision><decision><nature>MODIFICATION(S) STATUTAIRE(S)</nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte><acte><date_acte>2007-10-29</date_acte><num_acte>04</num_acte><type_acte>PA</type_acte><type_acte_libelle>PROCES VERBAL</type_acte_libelle><nbpages_acte>4</nbpages_acte><decision><nature>TRANSFERT DE SIEGE SOCIAL D'UN GREFFE EXTERIEUR</nature><libelle>ANCIEN SIEGE : 7 RUE BOULINEAU 94250 GENTILLY</libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>7803</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>04241</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>16261</num_depot><date_depot>2008-11-07</date_depot><acte><date_acte>2008-10-09</date_acte><num_acte>01</num_acte><type_acte>09</type_acte><type_acte_libelle>STATUTS APRES TRANSFERT DE SIEGE</type_acte_libelle><nbpages_acte>18</nbpages_acte><mode_diffusion><mode type="C"></mode><mode type="T"></mode></mode_diffusion></acte><acte><date_acte>2008-10-09</date_acte><num_acte>02</num_acte><type_acte>PH</type_acte><type_acte_libelle>PROCES VERBAL D'ASSEMBLEE MIXTE</type_acte_libelle><nbpages_acte>23</nbpages_acte><decision><nature>TRANSFERT DE SIEGE SOCIAL D'UN GREFFE EXTERIEUR</nature><libelle></libelle></decision><decision><nature>MODIFICATION(S) STATUTAIRE(S)</nature><libelle></libelle></decision><decision><nature>DEMISSION DE DIRECTEUR GENERAL</nature><libelle></libelle></decision><decision><nature>AUGMENTATION DE CAPITAL</nature><libelle></libelle></decision><mode_diffusion><mode type="C"></mode><mode type="T"></mode></mode_diffusion></acte></depot_acte><depot_acte><num_gest><greffe>7501</greffe><dossier_millesime>08</dossier_millesime><dossier_statut>B</dossier_statut><dossier_chrono>01601</dossier_chrono></num_gest><num_siren>494967938</num_siren><num_depot>81004</num_depot><date_depot>2008-09-09</date_depot><acte><date_acte>2008-09-08</date_acte><num_acte>01</num_acte><type_acte>OE</type_acte><type_acte_libelle>ORDONNANCE</type_acte_libelle><nbpages_acte>2</nbpages_acte><decision><nature></nature><libelle></libelle></decision><mode_diffusion><mode type="T"></mode><mode type="C"></mode></mode_diffusion></acte></depot_acte></liste_depot_acte></return></ns0:getProduitsWebServicesXMLResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

Actual result:
--------------
Nothing, I get the soap encoding error 

SoapFault exception: [Client] SOAP-ERROR: Encoding: Violation of encoding rules in infogreffe.php:81
Stack trace:
#0 [internal function]: SoapClient->__call('getProduitsWebS...', Array)
#1 infogreffe.php(81): SoapClient->getProduitsWebServicesXML('<demande><emett...')
#2 {main}<br/>

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports

 [2011-03-11 18:08 UTC] benjamin-richard at wanadoo dot fr

Hi, 
did you find a solution to your problem ? i have the same on a PHP 5.3.3

Thanks

 [2013-02-18 00:33 UTC] php-bugs at lists dot php dot net

No feedback was provided. The bug is being suspended because
we assume that you are no longer experiencing the problem.
If this is not the case and you are able to provide the
information that was requested earlier, please do so and
change the status of the bug back to "Open". Thank you.

Issue

Guys, I’m stuck, banging my head off the desk for the past few hours.

I am trying to consume a service, and I have 8 other functions that I call that are almost IDENTICAL in nature to this one, but this one, results in a ‘SOAP-ERROR: Encoding: Violation of encoding rules’ error.

Heres the function call (wsdl omitted for security):

    function CanLoadProduct($data){

    $client = new SoapClient('wsdl-url');

    $params = array('username'   => $this->username,
                    'password'  => $this->password,
                    'prod'      => $data['productid'],
                    'mdn'       => $data['mdn']);

    try {
        $reply = $client->__soapCall("CanLoadProduct", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        print_r($params);
        die();
    }

    if( $reply['result'] == 1 ){
        return TRUE;        // 1 = true
    } else {
        return FALSE;
    }

}

Ok so this function, connects to a webservice, the required elements are:
username, password, prod, mdn, all 4 of which I supply as part of the $params array. Username/Pass are defined earlier, and do work fine, as the other 8 functions consume the web service without any problems.

The $data[] array (that I pass to the function), contains:
$data[‘productid’]
$data[‘mdn’]
nothing else is used.

I am getting

SOAP-ERROR: Encoding: Violation of encoding rules

for some unexplained reason, and Googling this error gets me nowhere. Anyone else run into this? Running PHP 5.2.9-2. The strange thing is this is identical to this function which works 100%:

    function GetPIN($productid){

    $client = new SoapClient('wsdl-url');

    $params = array('username'  => $this->username,
                    'password'  => $this->password,
                    'prod'      => $productid);

    try {
        $reply = $client->__soapCall("GetPIN", $params);
    } catch (Exception $e) {
        echo 'Error: ',  $e->getMessage(), "n";
        die();
    }
        return $reply;
}

Here is the WSDL (should have posted this first):

<?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" 
    xmlns:tns="ready:test" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
    xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="ready:test">
<types>
<xsd:schema targetNamespace="ready:test"
>
 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
</xsd:schema>
</types>
<message name="CanLoadProductRequest">
  <part name="username" type="xsd:string" />
  <part name="password" type="xsd:string" />
  <part name="prod" type="xsd:string" />    
  <part name="mdn" type="xsd:string" />
  <part name="esn" type="xsd:string" /></message>
<message name="CanLoadProductResponse">
  <part name="result" type="xsd:int" /></message>
<portType name="CanLoadProductPortType">
  <operation name="CanLoadProduct">
    <input message="tns:CanLoadProductRequest"/>
    <output message="tns:CanLoadProductResponse"/>
  </operation>
</portType>

<binding name="CanLoadProductBinding" type="tns:CanLoadProductPortType">
  <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
  <operation name="CanLoadProduct">
    <soap:operation soapAction="{url-removed}" style="rpc"/>
    <input>
        <soap:body use="encoded" namespace="" 
           encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </input>
    <output>
        <soap:body use="encoded" namespace="" 
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
    </output>
  </operation>
</binding>
<service name="CanLoadProduct">
  <port name="CanLoadProductPort" binding="tns:CanLoadProductBinding">

    <soap:address location="{url-removed}"/>
  </port>
</service>
</definitions>

Solution

It looks like you have a type mismatch somewhere, either while assembling your request (one of the parameters is not of type string), or the server returns something other than an int (violating the WSDL response definition and thus causing the client to consider the response invalid, as it expects something else).

  • To test the first case, ensure casting all parameters to string first
  • To test the second case, create your SoapClient with the trace option set to true in order to gain access to the actual XML answer from the server via $client->__getLastResponse() afterwards (You can use this for request debugging also via __getLastRequest()).

Some additional observations/questions:

  • According to the posted WSDL, the ‘CanLoadProductRequest’ has a fifth param ‘esn’, which you do not supply in your function call.
  • Any reason why you use $client->__soapCall("CanLoadProduct", $params) instead of $client->CanLoadProduct($username, $password, etc.)? (The first version is a lower level variation which is intended to be used for non_WSDL scenarios. The second version might give you a more detailed error/exception)
  • Can you test the SOAP Call to CanLoadProductRequest by some other means? The error could be on the server side, trying to return a result type that does not fit the WSDL definition.

Answered By – Henrik Opel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

btakggn9c

WTF?, why the hell is every PHP developer saying my webservice is returning Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules – and there’s no problem with those using .NET, or parsing the XML response over HTTP GET/POST

Ok, let’s break down the problem.
1. It’s not a problem with PHP,it’s your WSDL, so here’s how to diagnose it.

Take this simple code snippet

$client = new SoapClient(“http://www.regcheck.org.uk/api/reg.asmx?wsdl”);
$params = array (
“RegistrationNumber” => “TNZ6972”,
“username” => “**Your Username**”
);
$response = $client->__soapCall(‘Check’, array($params));
print_r($response);

Now, take a copy of the WSDL, and save it as a text file, so you can edit it easily, i.e.

http://www.regcheck.org.uk/php.wsdl , then using HTML style comments, take out everything you can until you get a minimum working version. – i.e. a call that returns “something“, not all the data, but “something

<s:complexType name=”Vehicle>

<s:element minOccurs=”0 maxOccurs=”1 name=”vehicleJson type=”s:string/>

<s:element minOccurs=”0 maxOccurs=”1 name=”vehicleXml type=”s:string/>

<s:element minOccurs=”0 maxOccurs=”1 name=”numberOfSeats type=”s:string/>

<s:element minOccurs=”0 maxOccurs=”1 name=”carValue type=”s:string/>

<s:element minOccurs=”0 maxOccurs=”1 name=”immobiliser type=”s:string/>

<!– <s:element minOccurs=”0 maxOccurs=”1 name=”vehicleData> … –>

I had a hunch it was the VehicleData object, since it was the most complex type in the response, so I commented that out – and I now had a minimum working version.

After that, I progressively commented out elements within the VehicleData type, until I got my maximum working version – i.e. as much data as possible without it breaking.

At that point, I hit upon this:

<s:element minOccurs=”0″ maxOccurs=”1″ name=”CarModel”> <s:complexType> <s:simpleContent> <s:extension base=”s:integer“> <s:attribute name=”type” type=”s:NCName” /> </s:extension> </s:simpleContent> </s:complexType> </s:element>

Which was the point at which the webservice stopped returning data, and starting throwing the Uncaught SoapFault exception: [Sender] SOAP-ERROR: Encoding: Violation of encoding rules – and it did look odd, since I new that “CarModel” should be a string, not an integer.

Looking at the underlying C# code, the error was obvious

[System.Xml.Serialization.XmlTextAttribute(DataType=”integer“)]
public string Value {

There is no way that Value could both be a string and an integer, so I changed it to

[System.Xml.Serialization.XmlTextAttribute()]
public string Value {

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Socket error 10060 connection timed out как исправить
  • Soap error encoding object has no property
  • Socket error 10060 connection refused
  • Socket error 10056
  • Socket error 10055 буфер полон

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии