【问题标题】:looping through json data from url using php使用php从url循环遍历json数据
【发布时间】:2017-09-21 01:57:25
【问题描述】:

您好,我正在尝试使用以下代码回显从我正在使用的 api 返回的数据:

<?php

ini_set("include_path", '/home/matthewt/php:' . ini_get("include_path") );
// This sample uses the Apache HTTP client from HTTP Components 
(http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$url = $request->getUrl();

$headers = array(
    // Request headers
    'Ocp-Apim-Subscription-Key' => 'my_id',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_GET);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

到目前为止,一切都很好,返回的 json 数据基本上如下所示:(我缩短了字段数量以节省空间)

[{"GameID":49810,"Season":2017},{"GameID":49811,"Season":2017}]

我需要知道的是如何遍历这些数据以打印出每场比赛的结果。我知道我必须使用这样的东西:

$arr = json_decode();

foreach($arr as $item) { //foreach element in $arr
    $game_id = $item['GameID']; //etc
}

但我不确定需要解码什么...是 $response 吗?

谢谢

【问题讨论】:

    标签: php json


    【解决方案1】:

    如果$response-&gt;getBody() 包含您的 json,然后 json_decode 它,那么这将是您可以循环的对象数组。

    所以试试这个:

    // snip
    try
    {
        $response = $request->send();
        $arr = json_decode($response->getBody());
    
        foreach((array) $arr as $item) { //foreach element in $arr
            echo $item->GameID; //etc
            echo $item->Season; //etc
        }
    }
    catch (HttpException $ex)
    {
        echo $ex;
    }
    

    【讨论】:

    • np,快乐编码。
    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2017-01-30
    • 1970-01-01
    相关资源
    最近更新 更多