views:

103

answers:

4

How can i call a web service from php

+1  A: 

Use the curl function:

http://php.net/manual/en/book.curl.php

Assuming you are using a GET request to connect to a RESTful API:

$url = "http://the-api-you-want/?the-args=your-args&another-arg=another-arg"; 
$ch = curl_init(); // start CURL
curl_setopt($ch, CURLOPT_URL, $url); // set your URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
$json = curl_exec($ch); // connect and get your JSON response 
curl_close($ch);

You can then use PHP's json_decode on the response if that is what you want to do.

Another option would be using Drupal's drupal_http_request function http://api.drupal.org/api/function/drupal_http_request/6

Finbarr
That would only work for RESTful services :p
Francisco Soto
Can u explain little bit more. I am new to CURL and i want to use json for data transfer
THOmas
Do you mean you are expecting to receive a JSON response, or you want to send JSON in your query?
Finbarr
I have a built in web service that contain all database functionalityI want to use json for both sending and receving data to and from from the web service
THOmas
A: 

I would reccommend you to be more specific in your Question. Wich Type of Web Service do you mean?

If you are using Rest Webservices, i can recommend Zend_Rest_Client, that comes with the Zend Framework. I think the Zend Framework also provides Stuff for SOAP Services.

Paul Weber
I am using drupal cms
THOmas
A: 

Use curl or the Zend_Http_Client library from Zend Framework (You don't need the entire Zend Framework to use the library). If the service you are calling is sending a JSON response, then you'll have to parse it in PHP using json_decode.

Abhinav
A: 

Good Read : How to easily consume webservice in PHP ? wsdl2php as this answer points out was useful for me.

Rachel