如何格式化以下输出(在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"]
答案 0 :(得分:0)
如果要输出为HTML,请尝试在输出前添加<pre>
标签:
<pre><?= json_encode($result, JSON_PRETTY_PRINT); ?></pre>
这应该产生以下输出:
{
"_total": 872,
"streams": [
{
"_id": 30799425120,
"game": "Overwatch",
"broadcast_platform": "live",
"community_id": '',
"community_ids": [],
"viewers": 6104,
"video_height": 900,
"average_fps": 60,
"delay": 0,
"created_at": '...'
}
]
}
希望有帮助。