Ошибка looks like we got no xml document

I’m trying to create a web service but before I do I’m trying to get a simple example that I found on the internet to work first but I keep getting the following error:

Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document in C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php:20 Stack trace: #0 [internal function]: SoapClient->__call('getStockQuote', Array) #1 C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php(20): SoapClient->getStockQuote(Array) #2 {main} thrown in C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php on line 20

I am using nusoap v1.94

My web service code looks like this:

function getStockQuote($symbol) {
$price = '1.23';
return $price;
}

require('nusoap.php');

$server = new soap_server();

$server->configureWSDL('stockserver', 'urn:stockquote');

$server->register("getStockQuote",
            array('symbol' => 'xsd:string'),
            array('return' => 'xsd:decimal'),
            'urn:stockquote',
            'urn:stockquote#getStockQuote');

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
                  ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);

I know one cause is to have whitespace before or after your php tags in your server script but thats not the case. It has been driving me mad for hours! Any help would be much appreciated.

asked Nov 30, 2010 at 12:51

geoffs3310's user avatar

0

A byte order mark (BOM) would have the same effect as whitespace before the php tags.
Here you find a PHP snippet to detect and remove a BOM. Be sure to configure you editor to not insert the BOM again.

answered Nov 30, 2010 at 15:49

rik's user avatar

rikrik

8,5621 gold badge26 silver badges21 bronze badges

0

Pretty late but adding my fix to benefit of others. I have got similar error when I changed my Apache server from 2.2 to 2.4 and PHP 5.4.10 to 5.6.18 on windows. Client app used php 5.6.1. To fix the problem, I have done the following:

  1. Passed SOAP version parameter to SoapClient:

    ‘soap_version’ => SOAP_1_1

  2. On the server php.ini configuration file I have added:

    always_populate_raw_post_data = -1

answered Feb 16, 2016 at 10:35

mvsagar's user avatar

mvsagarmvsagar

1,9682 gold badges17 silver badges19 bronze badges

0

A bit late, but this kinda error is often caused by server-side (SOAP sense) problem :

  • print/echo content
  • rik’s answer too
  • mistake (eg I was currently having this error because of a miswritten filename in an include, generating an include error instead of executing the script…)
  • bad parameter in SOAP server
  • not the same compression level both sides (if compression used)

This message just inform you that the SOAP client did not receive well-formatted XML (eg. an error message instead of XML).

answered Sep 7, 2012 at 13:24

Benj's user avatar

BenjBenj

1,1847 gold badges26 silver badges57 bronze badges

0

set always_populate_raw_post_data = -1 in php.ini file (by removing the ; ) and then restart the server. It worked fine for me.

answered Jan 10, 2017 at 13:09

Ipsita Rout's user avatar

Ipsita RoutIpsita Rout

4,9154 gold badges36 silver badges40 bronze badges

0

This error appears also if a soap XML response contains special Unicode characters.
In my case it was REPLACEMENT CHARACTER (U+FFFD).

In details, inner function of the SoapClient xmlParseDocument sets xmlParserCtxtPtr->wellFormed property as false after parsing. It throws soap fault with looks like we got no XML document.

https://github.com/php/php-src/blob/master/ext/soap/php_packet_soap.c#L46

answered Oct 13, 2015 at 16:22

Andrei Zhamoida's user avatar

Andrei ZhamoidaAndrei Zhamoida

1,4581 gold badge20 silver badges30 bronze badges

I received this error when I was interacting with the Magento API which was loading a model, and it was throwing a warning before outputting the xml response which was causing the error.

To fix it you can simply turn off warnings on the API function: error_reporting(0);

answered May 21, 2012 at 5:32

Kus's user avatar

KusKus

2,52927 silver badges27 bronze badges

2

As far as I understand, the error of the SOAP parser when it comes invalid XML.

As it was with me.

  1. Turn on the display of the error
  2. performed in try-catch and in the catch call __getLastResponse
  3. I catch another error:

Warning: simplexml_load_string(): Entity: line 1: parser error :
xmlParseCharRef: invalid xmlChar value 26 in

  1. The first patient was PHP5.3. Once run the script on the PHP5.4, became more informative error — I swear on an invalid character, because of which, presumably, and fell SOAP parser.

As a result, I obtained the following code:

$params = array(...);
try
{
    $response = $client->method( $params );
}
catch(SoapFault $e)
{
    $response = $client->__getLastResponse();
    $response = str_replace("&#x1A",'',$response); ///My Invalid Symbol
    $response = str_ireplace(array('SOAP-ENV:','SOAP:'),'',$response);
    $response = simplexml_load_string($response);
}

If someone will tell in the comments what a symbol, I will be grateful.

answered Jul 21, 2016 at 8:29

borodatych's user avatar

borodatychborodatych

2964 silver badges9 bronze badges

2

Try to look into your server log. If you use nginx, please look into /var/log/nginx/error.log.
if «Permission denied» pop up, please change related dir owner.
Hope it will work.

answered May 14, 2014 at 8:25

Boush's user avatar

BoushBoush

1611 silver badge7 bronze badges

Another possible solution…

I had the same problem, I was getting crazy. The solution was simple.
Verifying my server.. cause it is a server error.
My error was that i had put «rcp» instead of «rpc».

answered Mar 23, 2015 at 17:16

Vrian7's user avatar

The post is old, but I think it’s always helpful, because I became crazy to not understand why this error appeared.

The solution for me was here: PHP SOAP client that understands multi-part messages?.

I had to extend the SoapClient to manage the MTOM encoding to obtain a clean XML as response.

I hope it can help someone.

answered Jun 1, 2020 at 8:39

Jiizen's user avatar

JiizenJiizen

1191 silver badge11 bronze badges

After years, here is another input I think would be useful for some; my case was a unit separator character returned in the body of the SAOP response, rendering the XML invalid. Therefore I needed to extend the SoapClient (a suggestion from another answer) and remove 0x1f character from the response like:

class SoapClientNoBOM extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        // strip away everything but the xml (including removal of BOM)
        $response = preg_replace('#^.*(<?xml.*>)[^>]*$#s', '$1', $response);
        // also remove unit separator
        $response = str_replace("x1f", '', $response);
        return $response;
    }
}

Now use SoapClientNoBOM instead of native SoapClient to instantiate a soap client.

answered Feb 2, 2021 at 21:51

Turab's user avatar

TurabTurab

1721 silver badge11 bronze badges

I’m trying to create a web service but before I do I’m trying to get a simple example that I found on the internet to work first but I keep getting the following error:

Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document in C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php:20 Stack trace: #0 [internal function]: SoapClient->__call('getStockQuote', Array) #1 C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php(20): SoapClient->getStockQuote(Array) #2 {main} thrown in C:Documents and SettingsgeoffMy DocumentsWebsitesjqueryindex.php on line 20

I am using nusoap v1.94

My web service code looks like this:

function getStockQuote($symbol) {
$price = '1.23';
return $price;
}

require('nusoap.php');

$server = new soap_server();

$server->configureWSDL('stockserver', 'urn:stockquote');

$server->register("getStockQuote",
            array('symbol' => 'xsd:string'),
            array('return' => 'xsd:decimal'),
            'urn:stockquote',
            'urn:stockquote#getStockQuote');

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)
                  ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);

I know one cause is to have whitespace before or after your php tags in your server script but thats not the case. It has been driving me mad for hours! Any help would be much appreciated.

asked Nov 30, 2010 at 12:51

geoffs3310's user avatar

0

A byte order mark (BOM) would have the same effect as whitespace before the php tags.
Here you find a PHP snippet to detect and remove a BOM. Be sure to configure you editor to not insert the BOM again.

answered Nov 30, 2010 at 15:49

rik's user avatar

rikrik

8,5621 gold badge26 silver badges21 bronze badges

0

Pretty late but adding my fix to benefit of others. I have got similar error when I changed my Apache server from 2.2 to 2.4 and PHP 5.4.10 to 5.6.18 on windows. Client app used php 5.6.1. To fix the problem, I have done the following:

  1. Passed SOAP version parameter to SoapClient:

    ‘soap_version’ => SOAP_1_1

  2. On the server php.ini configuration file I have added:

    always_populate_raw_post_data = -1

answered Feb 16, 2016 at 10:35

mvsagar's user avatar

mvsagarmvsagar

1,9682 gold badges17 silver badges19 bronze badges

0

A bit late, but this kinda error is often caused by server-side (SOAP sense) problem :

  • print/echo content
  • rik’s answer too
  • mistake (eg I was currently having this error because of a miswritten filename in an include, generating an include error instead of executing the script…)
  • bad parameter in SOAP server
  • not the same compression level both sides (if compression used)

This message just inform you that the SOAP client did not receive well-formatted XML (eg. an error message instead of XML).

answered Sep 7, 2012 at 13:24

Benj's user avatar

BenjBenj

1,1847 gold badges26 silver badges57 bronze badges

0

set always_populate_raw_post_data = -1 in php.ini file (by removing the ; ) and then restart the server. It worked fine for me.

answered Jan 10, 2017 at 13:09

Ipsita Rout's user avatar

Ipsita RoutIpsita Rout

4,9154 gold badges36 silver badges40 bronze badges

0

This error appears also if a soap XML response contains special Unicode characters.
In my case it was REPLACEMENT CHARACTER (U+FFFD).

In details, inner function of the SoapClient xmlParseDocument sets xmlParserCtxtPtr->wellFormed property as false after parsing. It throws soap fault with looks like we got no XML document.

https://github.com/php/php-src/blob/master/ext/soap/php_packet_soap.c#L46

answered Oct 13, 2015 at 16:22

Andrei Zhamoida's user avatar

Andrei ZhamoidaAndrei Zhamoida

1,4581 gold badge20 silver badges30 bronze badges

I received this error when I was interacting with the Magento API which was loading a model, and it was throwing a warning before outputting the xml response which was causing the error.

To fix it you can simply turn off warnings on the API function: error_reporting(0);

answered May 21, 2012 at 5:32

Kus's user avatar

KusKus

2,52927 silver badges27 bronze badges

2

As far as I understand, the error of the SOAP parser when it comes invalid XML.

As it was with me.

  1. Turn on the display of the error
  2. performed in try-catch and in the catch call __getLastResponse
  3. I catch another error:

Warning: simplexml_load_string(): Entity: line 1: parser error :
xmlParseCharRef: invalid xmlChar value 26 in

  1. The first patient was PHP5.3. Once run the script on the PHP5.4, became more informative error — I swear on an invalid character, because of which, presumably, and fell SOAP parser.

As a result, I obtained the following code:

$params = array(...);
try
{
    $response = $client->method( $params );
}
catch(SoapFault $e)
{
    $response = $client->__getLastResponse();
    $response = str_replace("&#x1A",'',$response); ///My Invalid Symbol
    $response = str_ireplace(array('SOAP-ENV:','SOAP:'),'',$response);
    $response = simplexml_load_string($response);
}

If someone will tell in the comments what a symbol, I will be grateful.

answered Jul 21, 2016 at 8:29

borodatych's user avatar

borodatychborodatych

2964 silver badges9 bronze badges

2

Try to look into your server log. If you use nginx, please look into /var/log/nginx/error.log.
if «Permission denied» pop up, please change related dir owner.
Hope it will work.

answered May 14, 2014 at 8:25

Boush's user avatar

BoushBoush

1611 silver badge7 bronze badges

Another possible solution…

I had the same problem, I was getting crazy. The solution was simple.
Verifying my server.. cause it is a server error.
My error was that i had put «rcp» instead of «rpc».

answered Mar 23, 2015 at 17:16

Vrian7's user avatar

The post is old, but I think it’s always helpful, because I became crazy to not understand why this error appeared.

The solution for me was here: PHP SOAP client that understands multi-part messages?.

I had to extend the SoapClient to manage the MTOM encoding to obtain a clean XML as response.

I hope it can help someone.

answered Jun 1, 2020 at 8:39

Jiizen's user avatar

JiizenJiizen

1191 silver badge11 bronze badges

After years, here is another input I think would be useful for some; my case was a unit separator character returned in the body of the SAOP response, rendering the XML invalid. Therefore I needed to extend the SoapClient (a suggestion from another answer) and remove 0x1f character from the response like:

class SoapClientNoBOM extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        // strip away everything but the xml (including removal of BOM)
        $response = preg_replace('#^.*(<?xml.*>)[^>]*$#s', '$1', $response);
        // also remove unit separator
        $response = str_replace("x1f", '', $response);
        return $response;
    }
}

Now use SoapClientNoBOM instead of native SoapClient to instantiate a soap client.

answered Feb 2, 2021 at 21:51

Turab's user avatar

TurabTurab

1721 silver badge11 bronze badges

Добрый день.
Начал разбираться с SOAP,набросал простенький сервис новостей и клиент под него и получил ошибку.

Что есть:
— сервис новостей,находится в папке news (все это крутится на OpenServre`e)
— soap-server,находится в папке news/soap
— wsdl файл news.wsdl,находится в папке news/soap
— soap-client,находится в папке localhost

Что я делаю:
Запускаю OpenServer,перехожу на localhost — вылетает «Операция Client вернула ошибку: looks like we got no XML document».
Проверил кодировки и BOM-символы,все в порядке.

Исходники:
— soap-server.php

<?php
require "../class/NewsDB.class.php";
class NewsService extends NewsDB{
	/* Метод возвращает новость по её идентификатору */
	function getNewsById($id){
		try{
			$sql = "SELECT id, title, 
					(SELECT name FROM category WHERE category.id=msgs.category) as category, description, source, datetime 
					FROM msgs
					WHERE id = $id";
			$result = $this->_db->query($sql);
			if (!is_object($result)) 
				throw new Exception($this->_db->lastErrorMsg());
			return base64_encode(serialize($this->sqlToArray($result)));
		}catch(Exception $e){
			throw new SoapFault('getNewsById', $e->getMessage());
		}
	}
	/* Метод считает количество всех новостей */
	function getNewsCount(){
		try{
			$sql = "SELECT count(*) FROM msgs";
			$result = $this->_db->querySingle($sql);
			if (!$result) 
				throw new Exception($this->_db->lastErrorMsg());
			return $result;
		}catch(Exception $e){
			throw new SoapFault('getNewsCount', $e->getMessage());
		}
	}
	/* Метод считает количество новостей в указанной категории */
	function getNewsCountByCat($cat_id){
		try{
			$sql = "SELECT count(*) FROM msgs WHERE category=$cat_id";
			$result = $this->_db->querySingle($sql);
			if (!$result) 
				throw new Exception($this->_db->lastErrorMsg());
			return $result;
		}catch(Exception $e){
			throw new SoapFault('getNewsCountByCat', $e->getMessage());
		}
	}
}
// Отключение кеширования wsdl-документа
ini_set("soap.wsdl_cache_enabled", "0");
// Создание SOAP-сервера
$server = new SoapServer("http://news/soap/news.wsdl");
// Регистрация класса
$server->setClass("NewsService");
// Запуск сервера
$server->handle();

-soap-client.php

<?php
$client = new SoapClient("http://news/soap/news.wsdl");
try{
// Сколько новостей всего?
	$result = $client->getNewsCount();
	echo "<p>Всего новостей: $result</p>";
// Сколько новостей в категории Политика?
	$result = $client->getNewsCountByCat(1);
	echo "<p>Всего новостей в категории Политика:$result</p>";
// Покажем конкретную новость
	$result = $client->getNewsById(5);
	$news = unserialize(base64_decode($result));
	var_dump($news);
}catch(SoapFault $e){
	echo 'Операция '.$e->faultcode.' вернула ошибку: '.$e->getMessage();
}

-news.wsdl

<?xml version ='1.0' encoding ='UTF-8' ?> 
<definitions name='News' 
		targetNamespace='http://news'
		xmlns:tns=' http://news'
		xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' 
		xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
		xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' 
		xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' 
		xmlns='http://schemas.xmlsoap.org/wsdl/'> 

	<message name='getNewsByIdRequest'> 
		<part name='id' type='xsd:integer'/> 
	</message> 
	<message name='getNewsByIdResponse'> 
		<part name='item' type='xsd:base64Binary'/> 
	</message> 

	<message name='getNewsCountResponse'> 
		<part name='count' type='xsd:integer'/> 
	</message>

	<message name='getNewsCountByCatRequest'> 
		<part name='cat_id' type='xsd:integer'/> 
	</message> 
	<message name='getNewsCountByCatResponse'> 
		<part name='count' type='xsd:integer'/> 
	</message>


	<portType name='NewsPortType'> 
		<operation name='getNewsById'> 
			<input message='tns:getNewsByIdRequest'/> 
			<output message='tns:getNewsByIdResponse'/> 
		</operation>
		<operation name='getNewsCount'> 
			<output message='tns:getNewsCountResponse'/> 
		</operation>	
		<operation name='getNewsCountByCat'> 
			<input message='tns:getNewsCountByCatRequest'/> 
			<output message='tns:getNewsCountByCatResponse'/> 
		</operation>	
	</portType>

	<binding name='NewsBinding' type='tns:NewsPortType'> 
		<soap:binding style='rpc' transport='http://schemas.xmlsoap.org/soap/http'/> 
		<operation name='getNewsById' /> 
		<operation name='getNewsCount' />
		<operation name='getNewsCountByCat' />  
	</binding> 

	<service name='NewsService'> 
		<port name='NewsPort' binding='NewsBinding'> 
			<soap:address location='http://news/soap/soap-server.php'/>
		</port> 
	</service> 
</definitions>

Буду признателен за любые идеи и уделенное время.

I’m having some strange problem while using SOAP with PHP.
Same function works with small data, but when my query returns more than X rows, it causes an exception «Uncaught SoapFault exception: [Client] looks like we got no XML document».

This is my code:

<?php
$cliente = new SoapClient(null, array('location' => $myserver,'uri' => 'urn:webservices'));
?>
<select id="actividad" name="actividad" size="1" style="height:40px; width: 100%;">
<?php
$acs = $cliente->get_actividades();
foreach($acs as $actividad) {
echo "<option value='".$actividad['idactividad']."'>".$actividad['descripcion']."</option>";
}                                       
?>
</select>

And this is server side:

public function get_actividades()
{
    $link = new mysqli($this->dbhost,$this->dbuser,$this->dbpass,$this->dbname);
    if (mysqli_connect_errno()) {
        return 0;
    }
    $query = "SELECT idactividad, codigo, descripcion FROM actividades";
    $datos = array();
    if ($stmt = $link->prepare($query)) {
        $stmt->execute();
        $stmt->store_result();
        $datos = $this->fetcharray($stmt);
        $stmt->free_result();
        $stmt->close();
        return $datos;
    } else { 
        return -1; 
    }           
}

That query results in about 37 rows. If I add a «LIMIT» clause to that query between 1 and 21 rows, it works fine, but more than that causes the no-xml-exception.

Can it be some memory problem?? Who could i fix it?

i’m trying to use magento soapV2 to create product, here is the script:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<?php


// Magento login information 
$mage_url = 'http://localhost/first/api/v2_soap?wsdl=1'; 

$mage_user = 'rayapi'; 
$mage_api_key = 'Abcd1234'; 
// Initialize the SOAP client 
$client = new SoapClient( $mage_url ); 

$session = $client->login( $mage_user, $mage_api_key );


$catalogProductCreateEntity = new stdClass();
$additionalAttrs = array();

$catalogProductCreateEntity->name = "product name";
$catalogProductCreateEntity->description = "description";
$catalogProductCreateEntity->short_description = "desc";
$catalogProductCreateEntity->status = "1";
$catalogProductCreateEntity->price = "99";
$catalogProductCreateEntity->tax_class_id = "2";
$catalogProductCreateEntity->websites = array(1,2);
$catalogProductCreateEntity->categories = array(7,15);
$catalogProductCreateEntity->status = 1;
$catalogProductCreateEntity->price = 45;
$catalogProductCreateEntity->tax_class_id = 2;
$catalogProductCreateEntity->weight = 1;

// send the request
$product = $client->catalogProductCreate($session, "simple", 9, 'test_sku', $catalogProductCreateEntity);

// end session and enjoy your updated products :)
$client->endSession($session);

var_dump($product);


?>

Error message:

Fatal error: Uncaught SoapFault exception: [Client] looks like we got no XML document in C:xampphtdocsfirstsoap.php:71 Stack trace: #0 C:xampphtdocsfirstsoap.php(71): SoapClient->__call('catalogProductC...', Array) #1 C:xampphtdocsfirstsoap.php(71): SoapClient->catalogProductCreate('7ab47f189292d99...', 'simple', 9, 'test_sku', Object(stdClass)) #2 {main} thrown in C:xampphtdocsfirstsoap.php on line 71

i tried use
$result = $client->catalogInventoryStockItemList($session, array(‘693’)); // //Products ID
print_r($result);

catalogInventoryStockItemList is work for me but catalogProductCreate not work.

i googled around but their solution not useful to me, how to solve this problem?

  • Ошибка logs fml client latest log
  • Ошибка logitech profiler was unable to detect any game controllers
  • Ошибка login live com
  • Ошибка login has illegal format
  • Ошибка login failed geometry dash