You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将远程PHP文件返回的JSON数据转换为PHP数组并调用?

解决方案

你当前的代码存在几个核心问题:

  • 直接用include引入远程文件会直接输出JSON内容,无法将数据捕获为变量供后续操作
  • 定义的data()函数仅创建了字段映射关系,但既未调用该函数,也未关联实际的JSON数据,且函数内的变量属于局部变量,外部无法访问
  • 输出逻辑完全错误,比如$datalist[0]["temp"]不符合数据结构,$deviation等变量从未定义过

正确实现步骤

  1. 获取远程JSON并转为PHP数组
    不能用include,改用file_get_contents获取远程文件内容,再通过json_decode转为关联数组:
// 获取远程JSON内容
$jsonContent = file_get_contents("filename.php");
// 转为关联数组(第二个参数设为true)
$weatherData = json_decode($jsonContent, true);

如果服务器禁用了allow_url_fopen,可以改用cURL实现:

$ch = curl_init("filename.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$jsonContent = curl_exec($ch);
curl_close($ch);
$weatherData = json_decode($jsonContent, true);
  1. 字段映射与页面输出
    可以用你定义的字段映射对应友好名称,也可直接使用原字段名输出。以下是完整可运行代码:
<?php
// 获取并解析数据
$jsonContent = file_get_contents("filename.php");
$weatherData = json_decode($jsonContent, true);

// 字段映射(可选,用于更友好的变量名)
$dataMap = [
    "currenttemp" => $weatherData["temp"],
    "deviation" => $weatherData["dev"],
    "last_processed" => $weatherData["city"],
    "country" => $weatherData["country"],
    "stations_processed" => $weatherData["count"],
];
?>

<table width="280" border="1">
<tbody>
<tr>
  <td>Current World Temp:</td>
  <td><?php echo $dataMap["currenttemp"]; ?></td> 
</tr>
<tr>
  <td>Deviation:</td>
  <td><?php echo $dataMap["deviation"]; ?></td>
</tr>
<tr>
  <td>Last Station Processed:</td>
  <td><?php echo $dataMap["last_processed"]; ?>, <?php echo $dataMap["country"]; ?></td>
</tr>
<tr>
  <td>Stations Processed Last Hour:</td>
  <td><?php echo $dataMap["stations_processed"]; ?></td>
</tr>
</tbody>
</table>

关键说明

  • json_decode($jsonContent, true)会将JSON字符串转为关联数组,方便通过键名直接访问对应值
  • 如果不需要字段映射,也可以直接用$weatherData["temp"]这种方式输出,代码会更简洁
  • 确保服务器允许访问远程URL(allow_url_fopen开启或cURL功能可用)

内容的提问来源于stack exchange,提问作者Steve Brueck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:23:25