Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

api - PHP Curl, Request data return in application/json

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

I would prefer it as jSON and the API Doc's say that it is available in jSON aswell as XML.

The Docs say...

The API currently supports two types of response format: 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 do I generate the Accept Header of applixation/json 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;

The echo of result is just returning XML formatted data.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should modify the code where you set the HTTP headers in your request. You weren't specifying the Accept header

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

This should sent the HTTP request to the API's URL with the information that you would like to get the response in the particular format.

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

  • The Accept header is a request header and it specifies the acceptable type of the response's body
  • The Content-Type header is both a request and a response header and it specifies the format of the body of the request/response

Example of the HTTP requests could look something like this (often, the request contains only the header part):

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

And the response could look something like that:

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...