【发布时间】:2014-09-16 08:09:30
【问题描述】:
我正在尝试从 API 中获取一些数据,现在我将其作为 XML 取回。
我更喜欢它作为 JSON,API 文档说它在 JSON 和 XML 中都可用。
文档说...
API 目前支持两种响应格式:XML 和 JSON
您可以使用请求中的 HTTP Accept 标头指定所需的格式:
接受:应用程序/xml 接受: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;
结果的回显只是返回 XML 格式的数据。
提前致谢。
【问题讨论】:
-
文档说
Accept,但你在CURLOPT_HTTPHEADER中使用Content-Type -
使用 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));