【发布时间】:2018-10-16 05:37:35
【问题描述】:
如何格式化以下输出(在 PHP 中使用 cURL 将 json 对象解析为数组并在 HTML 中显示格式正确的文本)
function curlTwitch() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/kraken/streams/?game=Overwatch");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array (
'Accept: application/vnd.twitchtv.v5+json',
'Client-ID: x8j9dhw66qkgbsw67bfwtos4hyfeww'
));
$result = curl_exec($ch);
var_dump( json_decode($result, true) );
//echo json_encode($result, JSON_PRETTY_PRINT);
}
我当前的输出以不可读的格式填充页面,并显示为:
array(2) { ["_total"]=> int(872) ["streams"]=> array(25) { [0]=> array(14) {
["_id"]=> int(30799425120) ["game"]=> string(9) "Overwatch"
["broadcast_platform"]=> string(4) "live" ["community_id"]=> string(0) ""
["community_ids"]=> array(0) { } ["viewers"]=> int(6104) ["video_height"]=>
int(900) ["average_fps"]=> int(60) ["delay"]=> int(0) ["created_at"]
【问题讨论】:
-
你能展示你想要的html代码布局吗?
-
我最终希望能够解析输出并在最终结果中分别显示每个节点。截至目前,我只想看看结构。类似于:imgur.com/a/oKC6qzu
-
好吧,如果你把它保存到一个新的var中,即
$result = json_decode($result, true);,那么你就可以像->$result['streams'][0]['game'];/$result['streams'][0]['broadcast_platform'];这样访问每个节点了 -
谢谢,这很有帮助,我会记住的!但是,我怎样才能在此处以可读格式查看/输出实际结构,以便我可以看到我可能想要解析的所有节点?
-
你可以使用
<pre>和print_r()->$results = json_decode($result, true); echo "<pre>".print_r($results, 1). "</pre>";。