Monday 8 September 2014

How to get XML/JSON content from a specified URL address ?

 XML (along with JSON) becomes the standart format to render data through internet (cf. consumption of web services).

One way to solve that issue is to use the cURL library (the client URL library) :

Here below is the PHP function I have been using in such case :

/**
* @param str $url
* @return str $content
*/
    function URLToXml($url)
    {
       // create curl resource
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $content = curl_exec($curl);
     
        //close curl resource to free up system resources

        curl_close($curl);

        return $content;
    }


Note :
"For accessing services we need an HTTP client. We can also use file_get_contents (http://www.php.net/file_get_contents) to access not only local files but
also those located on remote servers over HTTP.
However, file_get_contents uses GET, you would need considerable extra work to use a different verb like POST. Also, fopen wrappers need to be enabled to let file_get_contents() access remote files. System administrators may disable fopen wrappers due to security concerns.


The solution to the limitations associated with file_get_contents is to use an HTTP client library such as CURL (http://www.php.net/curl). CURL PHP API is a wrapper of libcurl (http://curl.haxx.se/libcurl/), a library that allows you to communicate using many different types of protocols. It supports HTTP verbs such as POST and PUT in addition to GET.


 [..]
HTTP verbs and how they apply while using REST web services:
GET : Retrieves a resource identified by a URI.
POST : Sends a resource to the server. Updates the resource in the location identified by the URI.
PUT : Sends a resource to the server, to be stored in the location identified by the URI.
DELETE : Deletes a resource identified by a URI.
HEAD : Retrieves the metadata of a resource identified by the URI.

"
(extracted from RESTful PHP Web Services, Samisa Abeysinghe