php - 通过 PHP 从 url 获取 JSON 数据
问题描述
我正在尝试使用 php 来制作货币转换器。但是,如您所见,如果我在本地下载 JSON,重新构建它并通过file_get_contents()
.
JSON:
{"status":true,"data":[{"buy_rate":"19.00","sell_rate":"19.20","currency":"China Yuan","flagicon":"CN","countrycode":"CNY"},{"buy_rate":"1.13","sell_rate":"1.14","currency":"Japanese Yen","flagicon":"jp","countrycode":"JPY"},{"buy_rate":"166.00","sell_rate":"167.65","currency":"UK Pound Sterling","flagicon":"GB","countrycode":"GBP"},{"buy_rate":"33.70","sell_rate":"34.05","currency":"Saudi Riyal","flagicon":"SA","countrycode":"SAR"},{"buy_rate":"93.75","sell_rate":"94.70","currency":"Australian Dollar","flagicon":"AU","countrycode":"AUD"},{"buy_rate":"34.50","sell_rate":"34.85","currency":"U.A.E Dirham","flagicon":"AE","countrycode":"AED"},{"buy_rate":"96.00","sell_rate":"96.95","currency":"Canadian Dollar","flagicon":"ca","countrycode":"CAD"},{"buy_rate":"129.50","sell_rate":"130.80","currency":"US Dollar","flagicon":"us","countrycode":"USD"},{"buy_rate":"148.00","sell_rate":"149.50","currency":"Euro","flagicon":"eu","countrycode":"EUR"},{"buy_rate":"1.00","sell_rate":"1.00","currency":"Pakistani Rupee","flagicon":"pk","countrycode":"PKR"}]}
代码:
<?php
$url = 'list.JSON';
$data = file_get_contents($url);
$output = json_decode($data);
foreach ($output as $outputs): ?>
<tr>
<td><?php echo $outputs->buy_rate; ?></td>
<td><?php echo $outputs->sell_rate; ?><td>
<td><?php echo $outputs->currency; ?><td>
<td><?php echo $outputs->flagicon; ?></td>
<td><?php echo $outputs->countrycode; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
解决方案
您只需要通过file_get_contents
(通过示例)获取内容并使用
json_decode
这是一个例子:
//this url is random
$content = file_get_contents('http://myjsondata.com');
//Decode json output to object
$output = json_decode($content);
//parse your object like you want
//I assume that my json contain a key 'data' HERE !
foreach($output->data as $data) {
//Do what you want here
}
希望这可以帮助
推荐阅读
- r - R:使用 plot_ly() 更改条形图中条形的宽度
- java - Selenium 拖放不适用于 Action 方法,是否有任何替代方法
- javascript - 未能在已部署的 emberjs 应用程序上的资源的“完整性”属性中找到有效的摘要
- sql - 将表条目从一个数据库传输到另一个数据库
- python - 总结字典内列表中相同键的值?
- javascript - JS画布显示在页面底部
- google-apps-script - 谷歌表覆盖现有数据库
- leaflet - 打开街道地图默认图块(传单)
- javascript - React - 在同一选项卡中打开一个链接,然后单击新链接中的一个按钮
- c# - EF Core await ToArrayAsync() 在 DbContext 中不起作用