如何与 Web XML/JSON API 交互?
我正在自己学习 php/xml/json 以及其他所有内容,并且我正在通过 API 来完成某些事情。他们有文档,但我仍然不明白 API 是如何工作的。他们为您提供了 GET 链接和 API 密钥,我知道您应该将 API 密钥放入请求链接中
我如何调用此链接?当它给你一个样本响应时,这意味着什么?
如果你的请求正确的话,响应应该会出来吗?
我是不是有点不明白了?
谢谢
I'm learning php/xml/json and everything else on my own and I was going through API's for certain things. They have documentations but I still don't get how API's work. They give you a GET link and API key, I know that you're supposed to put the API key inside the request link
How do I call this link? And what does it mean when it gives you a sample response?
Is the response supposed to come out if you got the request correct?
I'm a bit clueluess?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 PHP 中,您可能会遇到这样的情况:
$response
将包含您访问$url
时输出的任何xyz.com
字符串(它是如果您直接访问$url
,您会看到什么)。您的下一个工作是根据其数据结构(例如 XML、JSON 等)解析
$response
,以便其余代码可以使用它。有几个用于解析 XML 或 JSON 的 PHP 库。就我个人而言,我更喜欢使用 PHP 5 >= 5.2.0 中包含的
SimpleXMLElement
和json_decode()
。根据 API,如果它不理解请求
$url
,它可能会向您发送某种错误代码/响应结构,您可以在解析响应后检查该请求。如果
$response
返回 false,则通常与$url
通信时出现一些错误。我发现考虑这些
XHR
请求的直观方法是将参数(GET
参数)传递给函数(API URL)。 API URL 的响应就像函数的 return 语句。更新:
按照OP在评论中建议的Groupon API示例:
上面的代码将打印出芝加哥地区所有交易标题和网址的列表。如果您查看 Groupon API 页面上的
示例 JSON 响应
部分,它将为您提供将映射到关联数组$deals
的整个数据结构。如果用户向 API 提供了任何
GET
参数(例如,从 Web 表单),您将需要执行类似$division = "division_id=" 的操作。 urlencode($user_input);
。In PHP you might have something like this:
The
$response
will contain a string of whateverxyz.com
outputted when you accessed$url
(it's what you would see if you visited$url
directly).Your next job would be to parse
$response
based on its data structure (e.g XML, JSON, etc) so that it's usable by the rest of your code.There are several PHP libraries for parsing XML or JSON. Personally, I prefer to use
SimpleXMLElement
andjson_decode()
which is included with PHP 5 >= 5.2.0.Depending on the API, it will probably send you some sort of error code/response structure if it doesn't understand the request
$url
which you could check for after you parse the response.If
$response
returns false, then typically there was some error communicating with the$url
.I found that an intuitive way to think about these
XHR
requests is that you're passing arguments (GET
parameters) to a function (API URL). And the response from the API URL is like the return statement from a function.UPDATE:
API example for Groupon as suggested by OP in comments:
The above code would print out a listing of all deal titles and urls for the Chicago area. If you look at the
Sample JSON Response
sections on the Groupon API page, it will give you the entire data structure that would be mapped to the associative array$deals
.If any of the
GET
parameters to the API are provided by the user (e.g. from a web form), you will want to do something like$division = "division_id=" . urlencode($user_input);
.