I have the following codes copied directly from here:
http://www.codeproject.com/Tips/671437/Creating-Web-Service-Using-PHP-Within-Minutes
Server:
<?php
//call library
require_once ('nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('get_message');
// create the function
function get_message($your_name)
{
if(!$your_name){
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
Client:
<?php
require_once ('nusoap.php');
//Give it value at parameter
$param = array( 'your_name' => 'Cool Guy');
//Create object that referer a web services
$client = new soapclient('http://localhost/SOAPServer.php');
//Call a function at server and send parameters too
$response = $client->call('get_message',$param);
//Process result
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
When I try to access the client page, it shows me the following error:
FAULT: Code: (SOAP-ENV:Client
String: error in msg parsing: xml was empty, didn't parse!
I would only need this simple example working, what could be the problem?
Related
I am having some trouble regarding PHP NATS. I am getting and printing msg body values. Everything is working fine. Just returning result is the problem. Here is the code
function connect(){
require_once __DIR__ . "/../../vendor/autoload.php";
$connectionOptions = new \Nats\ConnectionOptions();
$connectionOptions->setHost('localhost')->setPort(4222);
$c = new Nats\Connection($connectionOptions);
$c->connect();
$c->request('sayhello', 'Marty McFly', function ($response) {
echo $response->getBody();
return $response->getBody();
});
}
echo is working and printing values, while return isn't returning anything if I use like this.
$res = connect():
print_r($res);
You are echoing from the scope of the anonymous function, and returning from the scope of connect() function.
One approach you can take is callback, you can make your function to take a Closure as an argument and run it from within connect() with the result as an argument:
function connect(\Closure $callback){
require_once __DIR__ . "/../../vendor/autoload.php";
$connectionOptions = new \Nats\ConnectionOptions();
$connectionOptions->setHost('localhost')->setPort(4222);
$c = new Nats\Connection($connectionOptions);
$c->connect();
$c->request('sayhello', 'Marty McFly', function ($response) use ($callback) {
echo $response->getBody();
$callback(response->getBody());
});
}
And you would use it as follows:
connect(function ($result) {
// here you've got an access to the $response->getBody() from connect function
});
I am trying to create a soap server with zend but when i try to make a request with Postman, I always receive 'Could not get any response'. In non-wsdl mode it works fine.
Please help!
public function wsAction()
{
if (isset($_GET['wsdl'])) {
header ("Content-Type: application/xml");
$autodiscover = new AutoDiscover();
$autodiscover->setClass('Order\Service\OrderService')
->setUri('http://example.gr/public/order/ws')
->setServiceName('OrderService');
echo $autodiscover->toXml();
return $this->getResponse();
}
else
{
$server = new Server('http://example.gr/public/order/ws?wsdl',array('cache_wsdl' => WSDL_CACHE_NONE,'trace'=>1));
$server->setClass('Order\Service\OrderService');
$server->handle();
}
}
I'm trying to consume a soap web service using nusoap and PHP 5.6.25 but I am having some errors. Here is the php code:
require_once 'nusoap-0.9.5/lib/nusoap.php';
$client = new nusoap_client('http://www.webservicex.net/ConvertTemperature.asmx?WSDL');
if($client->getError()){
echo 'Error';
} else {
echo 'nusoap is working';
}
Error:
Fatal error: Call to undefined function nusoap_client()
If you check any example on the internet about nusoap_client you can see that it looks like this:
$client = new nusoap_client("food.wsdl", true);
$error = $client->getError();
So when you create a new instances of class nusoap_client you need to add the word new before. So your code will look like this:
$client = new nusoap_client('http://www.webservicex.net/ConvertTemperature.asmx?WSDL');
if($client->getError()){
echo 'Error';
} else {
echo 'nusoap is working';
}
I am trying to consume WCF service from PHP . I need to pass a header field in soap client of PHP in order to consume it. Soap header will be something like this:
<header>
<LisenseKey>Lisense key goes here</LisenseKey>
</header>
The namespace for LisenseKey element is "http://mylinsensekeynamespace".
The method I want to consume in WCF is as follows:
public string function GetMessage(string name)
{
return "Hello , "+name;
}
Before the service is configured to validate header, I was consuming the service from PHP as follows and it is working perfectly:
try{
$client = new SoapClient("http://localhost:8181/?wsdl");
$param = new stdClass();
$param->name = "My Name";
$webService = $client->GetMessage($param);
print_r($webService);
}
catch(Exception $e)
{
echo $e->getMessage();
}
When after the service is configured to validate license key in header, I am trying to consume it like this and it is not working yet:
try{
$client = new SoapClient("http://localhost:8181/?wsdl");
$actionHeader = new SoapHeader("http://mycustomheader",'LisenseKey',"lisense key",true);
$client->__setSoapHeaders($actionHeader);
$param = new stdClass();
$param->name = "My Name";
$webService = $client->GetMessage($param);
print_r($webService);
}
catch(Exception $e)
{
echo $e->getMessage();
}
I already tried in so many different ways from online articles. How can I consume it? WCF service is using BasicHttpBinding and SOAP version should be 1.1. How to pass the header information to consume the service?
Following is the .NET WCF service code that validate for LicenseKey soap header for every request.
public class MyServiceMessageInspector : System.ServiceModel.Dispatcher.IDispatchMessageInspector
{
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel,
System.ServiceModel.InstanceContext instanceContext)
{
if (request.Headers.FindHeader("LisenseKey", "") == -1)
{
throw new FaultException("Lisense Key Was Not Provided");
}
var lisenseKey = request.Headers.GetHeader<string>("LisenseKey", "http://mycustomheader.com");
if (string.IsNullOrEmpty(lisenseKey))
{
throw new FaultException("Lisnse key should not be empty");
}
if (lisenseKey != "12345x")
{
throw new FaultException("Lisense key is not valid");
}
return instanceContext;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
}
}
public class MyServiceMessageInspectorBehaviour : Attribute, System.ServiceModel.Description.IServiceBehavior
{
public void AddBindingParameters(System.ServiceModel.Description.ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase,
System.Collections.ObjectModel.Collection<System.ServiceModel.Description.ServiceEndpoint> endpoints,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceDescription serviceDescription,
System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
{
foreach (var endpointDispatcher in channelDispatcher.Endpoints)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyServiceMessageInspector());
}
}
}
public void Validate(System.ServiceModel.Description.ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
}
Try calling the WCF service like this : $client->__soapCall("GetMessage", $param, NULL, $header);
I'm working in a codeigniter based project with integrated SOAP webservices, and I fail to load a model function inside a registered webservice function.
I have this 2 functions in SOAP webservice: hello and addcontact.
function hello($name) {
return 'Hello, ' . $name;
}
and
function addcontact($nombre, $apellido, $ciudad) {
$resultado=$this->modelo_turismo->addcontact($nombre, $apellido, $ciudad);
if($resultado){
return "Bienvenido $nombre $apellido. Tu eres de $ciudad.";
}else{
return "No se pudo agregar contacto.";
}
}
Function hello is simple and its working fine when service is consumed by client, unlike function addcontact that is showing this message when trying to be consumed:
Response not of type text/xml: text/html
As you can see, I'm loading a function within model that inserts a contact to database, but im not even returning any database data to echo or print.
As well I've tried some other things trying to load the model, I cant get rid of that message, so I tried this (I know its weird to use a function to insert like this in CodeIgniter but im trying to learn why that message come):
function addcontact($nombre, $apellido, $ciudad) {
$conexion = new mysql ("localhost","root","","turismo");
if ($conexion->connect_errno){
return "Failed to connect to MySQL: " . $conexion->connect_error;
}
$query = "INSERT INTO contactos (nombre, apellido, ciudad) VALUES ('$nombre', '$apellido', '$ciudad')";
$resultado = $conexion->query($query);
if($resultado){
return "Bienvenido $nombre $apellido. Tu eres de $ciudad.";
}else{
return "No se pudo agregar contacto.";
}
}
with that function I get this error again:
Response not of type text/xml: text/html
But if I change the in the connection line 'mysql' to 'mysqli' like this:
$conexion = new mysqli ("localhost","root","","turismo");
I get the expected result when loading client:
Bienvenido John Travolta. Tu eres de California.
I then suspected that the error I was getting loading the model was because in my database config file I had this line:
$db['default']['dbdriver'] = 'mysql';
so I tried to change the driver to 'mysqli' and no good results. I keep getting the same error:
Response not of type text/xml: text/html
BTW, this is the way im registering 'addcontact' function:
$this->nusoap_server->register('addcontact', // method name
array('nombre' => 'xsd:string',
'apellido' => 'xsd:string',
'ciudad' => 'xsd:string'), // input parameters
array('return' => 'xsd:string'), // output parameters
'urn:Turismo_WSDL', // namespace
'urn:Turismo_WSDL#addcontact', // soapaction
'rpc', // style
'encoded', // use
'Agregar reservacion' // documentation
);
and this is the client function, that consumes the function above:
function addcontact() {
$wsdl = site_url('Webservice/wsdl');
$client = new nusoap_client($wsdl, true);
$client-> soap_defencoding='UTF-8';
$client->decode_utf8 = true;
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result = $client->call('addcontact', array('nombre' => 'John', 'apellido'=>'Travolta', 'ciudad'=>'California'));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
}
So my question is, what I'm doing wrong? I can do the work with a manual connection like described above, but I want to work with the model as in CodeIgniter.
We can call the codeigniter models using instance variable
$ci =& get_instance();
Class soap
{
private $ci;
// set the CI classes to $CI
function __constuct(){
$this->ci = & get_instance ();
}
function callone(){
$resultado=$this->ci->modelo_turismo->addcontact($nombre, $apellido, $ciudad);
}
}
ci-> will provide the models from CI
Please refer this for more about codeigniter Instance variables
Codeigniter: Get Instance