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

PHP使用json_decode解析JSON后输出为空,如何提取指定歌曲相关字段

问题错误点
  • json_decode($data, true)传入第二个参数true时返回的是关联数组,不能用对象运算符->访问属性,必须用数组方括号[]读取
  • 字段层级遗漏了song节点:text和art字段都归属在now_playing下的song子节点中,并非直接挂载在now_playing层级下
正确提取代码
// 读取JSON数据
$jsonContent = file_get_contents('你的JSON接口地址');
// 解析为关联数组
$data = json_decode($jsonContent, true);

// 校验解析是否成功,可根据实际需求调整错误处理逻辑
if (json_last_error() !== JSON_ERROR_NONE) {
    die('JSON解析失败:' . json_last_error_msg());
}

// 1. 提取now_playing下song的text、art字段
$nowPlayingText = $data['now_playing']['song']['text'];
$nowPlayingArt = $data['now_playing']['song']['art'];
// 输出测试
echo '当前播放歌曲:' . $nowPlayingText . '<br>';
echo '当前播放歌曲封面:' . $nowPlayingArt . '<br><br>';

// 2. 遍历song_history提取每一项的song的text、art字段
echo '历史播放列表:<br>';
foreach ($data['song_history'] as $historyItem) {
    $songText = $historyItem['song']['text'];
    $songArt = $historyItem['song']['art'];
    echo '歌曲名:' . $songText . ',封面地址:' . $songArt . '<br>';
}

如果习惯用对象方式读取数据,只需要把json_decode的第二个参数改为false或者省略,对应访问方式调整为:

// 解析为对象
$data = json_decode($jsonContent);
// 对象方式读取字段
$nowPlayingText = $data->now_playing->song->text;

内容的提问来源于stack exchange,提问作者Jamie Warren

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:27:00