【问题标题】:how to read a response back from URL which is sending the response in json如何从以 json 格式发送响应的 URL 读取响应
【发布时间】:2011-08-24 02:24:27
【问题描述】:

我收到了一个 API url 提要,它以 JSON 格式返回响应,我被告知将标头设置为:

Accept: application/json
X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009

谁能告诉我如何解决这个问题?

【问题讨论】:

  • 您如何向 API 发出请求?一旦我们知道我们可以弄清楚如何设置标题。
  • @Nick,我对此也一无所知。我根本不知道如何继续前进。请指导我。

标签: php json url codeigniter response


【解决方案1】:

问题 1

我会使用PHP curl 库。

例如:

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json', 
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));

// grab URL and pass it to the browser
echo curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

请参阅curl_setopt() 以获取有关我在上面使用的CURLOPT_HTTPHEADER 等常量的更多信息。

来自 cmets 的问题 2

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json', 
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));

// grab URL and pass it to the browser
$json = json_decode(curl_exec($ch), true);

// close cURL resource, and free up system resources
curl_close($ch);

$json 现在包含响应的关联数组,您可以通过var_dump()查看结构。

【讨论】:

  • 好的,我知道了,你能告诉我如何解析它吗?!我的意思是如何在 php 中使用一些循环来获取它。
【解决方案2】:

如果您在 PHP 中使用 cURL,您可以在请求中设置自定义标头:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009'
));

【讨论】:

猜你喜欢
  • 2015-04-11
  • 2016-04-03
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多