如何使用Smarty解析YouTube API返回的JSON文件并排查代码问题
问题原因
- 遍历对象错误:你直接遍历了JSON解析后的根响应对象,实际视频数据存放在根对象下的
items数组中,需要遍历该数组 - 取值路径错误:
snippet是items数组内单个视频对象的子属性,不是直接挂载在items集合下的属性
正确实现代码
对象写法(默认情况)
{capture assign=feed}{cache_remote_file url="https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=Duf5UUT......"}{/capture} {$videoList = $feed|json_decode} {foreach from=$videoList->items item=video} <p> title : {$video->snippet->title} </p> <p> img : {$video->snippet->thumbnails->default->url} </p> {/foreach}
关联数组写法(兼容所有Smarty版本)
如果上述代码运行报错,可使用关联数组写法,json_decode传入第二个参数true即可返回关联数组:
{capture assign=feed}{cache_remote_file url="https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id=Duf5UUT......"}{/capture} {$videoList = $feed|json_decode:true} {foreach from=$videoList['items'] item=video} <p> title : {$video['snippet']['title']} </p> <p> img : {$video['snippet']['thumbnails']['default']['url']} </p> {/foreach}
内容的提问来源于stack exchange,提问作者Andrew Smith
相关产品推荐
相关产品推荐

