Main Contents

[PHP] Retourner un tableau avec NuSoap

novembre 5, 2010

Voilà une question qu’on me pose souvent, comment renvoyer un tableau à travers un WebService avec NuSoap.
Donc voilà une petite explication.

Comme pour tous les WS avec NuSoap, il faut définir l’objet renvoyer.
Par exemple ici, on va définir un contact comprenant un nom, prenom, site web et un téléphone. Puis on va définir un tableau de contact, le ContactArray

$serveur->wsdl->addComplexType(
   'Contact',
   'complexType',
   'struct',
   'all','',
   array(
      'nom' => array('name' => 'nom', 'type' => 'xsd:string'),
      'prenom' => array('name' => 'prenom', 'type' => 'xsd:string'),
      'web' => array('name' => 'web', 'type' => 'xsd:string'),
      'tel' => array('name' => 'tel', 'type' => 'xsd:int'),
   )
);
 
$serveur->wsdl->addComplexType(
   'ContactArray',
   'complexType',
   'array','',
   'SOAP-ENC:Array',array(),
   array(
      array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Contact[]')
   ),
   'tns:Contact'
);

Puis comme d habitude on définit la méthode du WS.

$serveur->register('getContacts',
                           array(), //pas de paramètre en entré
                           array('Contact' => 'tns:ContactArray')
               );

Donc getContacts retournera un ContactArray. Il ne reste plus qu’à définir getContacts.

function getContacts() { 
$result = array();
	$req="SELECT * FROM `Contacts`";
	$res=mysql_query($req);
	while($obj=mysql_fetch_object($res)) {
		$result[] = array( 'nom' => $obj->nom, 'prenom' => $obj->prenom,'email'=>$obj->email, 'tel'=>$obj->tel);
	}
return $result;
}

Et voilà!

Catégorie(s): Développement, Tutorial, Web | Comments (3)

3 Comments