通过PHP从网址中获取JSON数据

时间:2018-07-24 09:47:13

标签: php 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>

1 个答案:

答案 0 :(得分:0)

您只需要通过if (process.browser)(例如)获取内容并使用 file_get_contents

这里是一个例子:

json_decode

希望这会有所帮助

相关问题