【问题标题】:Formatting PHP Array from JSON Object in HTML从 HTML 中的 JSON 对象格式化 PHP 数组
【发布时间】: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>";

标签: php arrays json twitch


【解决方案1】:

如果您要输出到 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": '...'
        }
    ]
}

希望对您有所帮助。

【讨论】:

  • 谢谢,但由于某种原因,这让我可以在一行中输出所有内容。
  • 可以截图吗?否则不清楚,真的:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 2021-02-28
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多