PHP Curl,请求数据在application/json中返回

Stu*_*ett 10 php api curl

我试图从API获取一些数据,我现在以XML格式将其恢复.

我更喜欢它作为jSON和API Doc说它在jSON以及XML中都可用.

文件说......

API目前支持两种类型的响应格式:XML和JSON

您可以使用请求中的HTTP Accept标头指定所需的格式:

接受:application/xml Accept:application/json

那么如何在我的PHP代码中生成applixation/json的Accept Header?

我的PHP代码目前是:

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;
Run Code Online (Sandbox Code Playgroud)

结果的回显只是返回XML格式的数据.

提前致谢.

小智 21

您应该修改在请求中设置HTTP标头的代码.您没有指定Accept标题

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
Run Code Online (Sandbox Code Playgroud)

这应该将HTTP请求发送到API的URL,其中包含您希望以特定格式获取响应的信息.

编辑(如果这可能对某人有用):

  • 所述Accept报头是请求报头,并将其指定响应身体的可接受的类型
  • Content-Type报头既是请求和响应首部,并将其指定请求/响应的所述主体的所述格式

HTTP请求的示例可能看起来像这样(通常,请求只包含标题部分):

GET /index.html HTTP/1.1
Host: www.example.com
Accept: application/json
Run Code Online (Sandbox Code Playgroud)

响应可能看起来像这样:

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"
}
Run Code Online (Sandbox Code Playgroud)