我需要使用一个以 JSON 格式响应的 HTTP Web 服务。鉴于 Web 服务的 URL 已知,我如何在 php 中实现此目的?
最佳答案
这是你应该做的:
$data = file_get_contents(<url of that website>);
$data = json_decode($data, true); // Turns it into an array, change the last argument to false to make it an object
这应该能够将 JSON 数据转换为数组。
现在,解释一下它的作用。
file_get_contents()
本质上是获取远程或本地文件的内容。这是通过 HTTP 门户进行的,因此您不会因将此功能用于远程内容而违反隐私政策。
然后,当您使用 json_decode()
时,它通常会将 JSON 文本更改为 PHP 中的对象,但由于我们为第二个参数添加了 true
,因此它会返回一个改为关联数组。
然后你可以对数组做任何事情。
玩得开心!
关于php - 在 PHP 中解析来自 HTTP Web 服务 (JSON) 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17827872/