PHP Curl, request data return in application / json

I am trying to get some data from the API and I am returning it as XML at the moment.

I would prefer jSON and the Doc API to say that it is available in jSON as well as XML.

Documents say ...

Currently, the API supports two types of response formats: XML and JSON.

You can specify the desired format using the HTTP Accept header in the request:

Accept: application / xml Accept: application / json

So, how can I generate Accept in the applixation / json application header in my PHP code?

My PHP code at the moment is:

header('Content-Type: application/json'); $endpoint = "http://api.api.com"; // Initiate curl $ch = curl_init(); // Set The Response Format to Json curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json')); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Will return the response, if false it print the response curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set the url curl_setopt($ch, CURLOPT_URL,$endpoint); // Execute $result=curl_exec($ch); // Closing curl_close($ch); echo $result; 

An echo of the result simply returns the data in XML format.

Thanks in advance.

+7
api php curl
source share
1 answer

You must change the code in which you set the HTTP headers in your request. You did not specify an Accept header

 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); 

This should send an HTTP request to the API URL with the information you would like to receive in a specific format.

Edit (in case this might be useful to someone):

  • The Accept header is the request header and determines the valid response body type.
  • The Content-Type header is the request and response header, and it defines the format of the request / response body

An example of HTTP requests may look something like this (often a request contains only part of the header):

 GET /index.html HTTP/1.1 Host: www.example.com Accept: application/json 

And the answer might look something like this:

 HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Content-Type: application/json; charset=UTF-8 Content-Length: 24 { "hello": "world" } 
+13
source share

All Articles