This topic is locked

Webservices - JSON - Simple example

12/18/2019 12:09:04 PM
PHPRunner Tips and Tricks
fhumanes author


What does Wikipedia tell us about Web Services?
A web service is a technology that uses a set of protocols and standards that are used to exchange data between applications. Different software applications developed in different programming languages, and executed on any platform, can use web services to exchange data on computer networks such as the Internet. Interoperability is achieved through the adoption of open standards.
It has an interface described in a format that can be processed by a computer team (specifically in WSDL), through which it is possible to interact with it by exchanging SOAP messages, typically transmitted using XML serialization over HTTPS in conjunction with other web standards.


What does Wikipedia tell us about JSON?
JSON (acronym for JavaScript Object Notation, "JavaScript object notation") is a simple text format for data exchange. It is a subset of the literal notation of JavaScript objects, although, due to its wide adoption as an alternative to XML, it is considered (year 2019) a language-independent format.
One of JSON's supposed advantages over XML as a data exchange format is that it is much easier to write a parser for it. In JavaScript, a JSON text can be easily analyzed using the eval () function, something that (due to the ubiquity of JavaScript in almost any web browser) has been essential for it to have been accepted by the AJAX developer community.
What exercise do I want to introduce you?

My idea is that you can see how simple, fast and efficient it is to use PHP to create Webservices and to use JSON as a data transmission format.
To build the server part of the Webservices I use the Zend framework that makes everything very simple and that facilitates the WSDL interface, which will allow anyone to know how to access the service and what methods (functions) are published.
The example made in PHPRunner is very simple, it executes the client part of the Webservices, obtains through this mechanism the Municipalities of a Province and loads them in a table with an added field of the identification of the work session for the connected user, so that the transmitted data will be seen in a table, with different data for each connected user.
As you can see, the exercise makes no more sense to see the 2 technologies (Webservices and Json), plus a way of presenting the data obtained in this way, in the format that PHPRunner 10.2 knows how to do very well.
You can see the result of the example at https://fhumanes.com/consume_ws/. The "Municipio" option requests the Province code and brings, using the Webservices and Json data format, the Municipalities of that Province.
I will describe the sources that I understand are more interesting:
Files to build the Webservices Server
This confirmation file or this data is required for both the Server part and the Client part.
_configuracionwsdl.php



<?php

define("URI","http://localhost/consume_ws/server");

define("LOCATION_WSDL","http://localhost/consume_ws/server/server_wsdl.php");

define("SOAP_VERSION", "SOAP_1_2");

define("WSDL","http://localhost/consume_ws/server/server_wsdl.php?wsdl");

?>


To create the Webservices using Zend Framework, what is done is to create a class and the functions (webservices methods) that we need.
Very important is the comments part before the functions. The literal @param and @return will be used to establish the type of variable that the input parameters and the response variable will have.
In this case the code is:
_clasesAccesoMunicipios.php



<?php

class AccesoMunicipios {



/**

* Access Municipios of Provincia

*

* @param string $CodeProvincia

* @return string

*/



public function Municipios($CodeProvincia) {



$conn = new mysqli('localhost', 'root', 'humanes', 'runner_reports'); // conection to Mysql

if ($conn->connect_errno) { // If error conection to Mysql

echo "Lo sentimos, este sitio web está experimentando problemas.";

echo "Error: Fallo al conectarse a MySQL debido a: \n";

echo "Errno: " . $conn->connect_errno . "\n";

echo "Error: " . $conn->connect_error . "\n";

exit;

}

// execute SQL

$sql = "SELECT `idrp_municipio`, `CodigoMunicipio`, `NombreMunicipio` FROM rp_municipio where `CodigoProvincia` = '$CodeProvincia'";

if (!$result = $conn->query($sql)) {

// ¡Oh, no! The query error.

echo "Lo sentimos, este sitio web está experimentando problemas.";

echo "Error: La ejecución de la consulta falló debido a: \n";

echo "Query: " . $sql . "\n";

echo "Errno: " . $conn->errno . "\n";

echo "Error: " . $conn->error . "\n";

exit;

}

if ($result->num_rows === 0) {

// ¡Oh, not record

echo "Lo sentimos. No se pudo encontrar una coincidencia para el Código $CodeProvincia. Inténtelo de nuevo.";

exit;

}

$municipios = $result->fetch_all(MYSQLI_ASSOC);

$municipios = json_encode($municipios, JSON_UNESCAPED_UNICODE); // convert Array to Json

// free resource of Mysql

$result->free();

$conn->close();

return $municipios;

}

}

?>


What this code does is to receive a parameter with the Province code, access the BD and retrieve all the Municipalities of that Province in an Array and then transform said Array to a JSON format, which is what it transmits.
The rest of the server code is:
_serverwsdl.php



<?php

require_once 'zend/vendor/autoload.php';

$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));

$loader->register();

require_once("configuracion_wsdl.php");

require_once("clases_AccesoMunicipios.php");

try {

if (isset($_GET['wsdl'])) {

$autodiscover = new Zend\Soap\AutoDiscover();

$autodiscover->setClass('AccesoMunicipios')->setUri('LOCATION_WSDL');

header('Content-type: application/xml');

echo $autodiscover->generate()->toXml();

} else {

$servidorSOAP = new SOAPServer(WSDL);

$servidorSOAP->setClass('AccesoMunicipios');

$servidorSOAP->handle();

}

} catch (SOAPFault $f) {

print $f->faultstring;

}

?>


Normally, to check that the Webservice works and has no problems, I usually write an example of a Client. This client has 2 parts, one to test the Class (without the Webservices protocol) and another as a Webservices Client. In this case the example is:
_clientwsdl.php



<?php

// Client example to test the webservice server

require_once("configuracion_wsdl.php");

/*

* Class test directly, without communications

*/

/*

require_once("clases_AccesoMunicipios.php");

$AccesoMunicipios = new AccesoMunicipios();

// Test

$result = $AccesoMunicipios->Municipios('01');

print_r($result);

$result = json_decode($result,true);

print_r($result);

*/

try {

$client = new SoapClient(WSDL, array('location' => LOCATION_WSDL)); // Server wsdl access

$result = $client->Municipios('01'); // Execution of a webservices method

$result = json_decode($result,true); // Array decoding in JSON format

// print_r($result);

foreach ($result as &$municipio) { // Test to print the set of ARRAY elements

$id = $municipio['idrp_municipio'];

$CodigoMunicipio = $municipio['CodigoMunicipio'];

$NombreMunicipio = $municipio['NombreMunicipio'];

echo "id = $id, Código= $CodigoMunicipio, Nombre= $NombreMunicipio <BR>";

}



} catch (SOAPFault $f) { // In case of error, printing of the same

print $f->faultstring;

}

?>


In this example, what is discussed is the Class test.
As you can see, it is very simple to build the server part of the webservices in PHP and for those who have done it in Java or another similar programming language, you can assess much better how simple, fast and efficient it is.
In this section I explain the code made in PHPRunner
We collect the ID of the session, to establish it as a key to the information we will recover.
Event _after_applicationinitialized

$_SESSION['session_name']=session_id();


In the table "temp_municipio" we code the events:
_after_tableinitialized



$session_name = $_SESSION['session_name'];

$query->addWhere("SessionName = '$session_name'"); // filter only this session


In the action of «ADD» the event is codified:

_before_new_record_isadded



$session_name = $_SESSION['session_name'];

$provincia = $values['CodigoProvincia'];

// Client WebServices

require_once("server/configuracion_wsdl.php");

$client = new SoapClient(WSDL, array('location' => LOCATION_WSDL)); // Server wsdl access

$result = $client->Municipios($provincia); // Execution of a webservices method

$result = json_decode($result,true); // Array decoding in JSON format

// Delete record of Municipios after

$sql = "delete FROM temp_municipio where SessionName = '$session_name'";

DB::Exec($sql);

// Inser new record of Municipìos

foreach ($result as &$municipio) { // Test to print the set of ARRAY elements

$id = $municipio['idrp_municipio'];

$CodigoMunicipio = $municipio['CodigoMunicipio'];

$NombreMunicipio = $municipio['NombreMunicipio'];

$sql = "INSERT INTO temp_municipio

(`SessionName`, `CodigoProvincia`, `CodigoMunicipio`, `NombreMunicipio`)

Values ('$session_name','$provincia','$CodigoMunicipio','$NombreMunicipio')";

DB::Exec($sql);

}

//********** Redirect to another page ************

header("Location: temp_municipio_list.php");

exit();

return false;


And that's how simple everything has been. Access the Server, retrieve all the Municpios in JSON format, pass them to an array and one to one of the records inserts them in the temporary table with the corresponding session ID.
As always, in my blog there are all the sources to be downloaded and for any questions or what you need, you can contact me through my email [email="fernandohumanes@gmail.com"]fernandohumanes@gmail.com[/email]

C
CTom 12/19/2019

Many many thanks, awesome example.