PHP卷曲,在应用程序/ JSON请求数据返回 [英] PHP Curl, Request data return in application/json

查看:128
本文介绍了PHP卷曲,在应用程序/ JSON请求数据返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个API得到一些数据,我得到它回来的时刻为XML。

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

我想preFER它作为JSON和API文档的说,它是提供JSON作为藏汉XML。

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

文档说...

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

The API currently supports two types of response format: XML and JSON

您可以使用HTTP接受请求标头指定所需的格式为:

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

接受:应用/ XML
  接受:应用/ JSON

Accept: application/xml Accept: application/json

那么,如何生成接受applixation / JSON的头在我的PHP code?

So how do I generate the Accept Header of applixation/json in my PHP code?

在此刻我的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;

结果的回声只是返回的XML格式的数据。

The echo of result is just returning XML formatted data.

先谢谢了。

推荐答案

在这里您在请求中设置HTTP头,您应该修改code。你没有指定接受

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'));

这应该发送的HTTP请求的API的信息,网址,你想获得在特定格式的响应。

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

HTTP请求的实例可能是这个样子(通常,请求仅包含头部分):

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

这篇关于PHP卷曲,在应用程序/ JSON请求数据返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆