首页 > 解决方案 > 通过 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>

标签: phpjson

解决方案


您只需要通过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
}

希望这可以帮助


推荐阅读