【问题标题】:Fetch, Decode and Re-encode JSON获取、解码和重新编码 JSON
【发布时间】:2013-08-01 12:42:21
【问题描述】:

我正在尝试根据一些 URL 参数从 Instagram 获取 JSON,然后对 JSON 进行解码,然后将所需的对象编码为我自己的 JSON 格式。虽然我知道这听起来有点荒谬,但这是必需的。我唯一的问题是,由于某种原因,它不会对 JSON 的每个部分进行编码,它只适用于一个项目。代码如下。

<?php

function instagram($count=16){

$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];


    $url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;

        $jsonData = json_decode((file_get_contents($url)));

$jsonData = json_decode((file_get_contents($url)));
    foreach ($jsonData->data as $key=>$value) {

            $response = array();
            $response["data"] = array();
            $data = array();
            $data["createdtime"] = $value->caption->created_time;
            $data["username"] = $value->caption->from->username;
            $data["profileimage"] = $value->caption->from->profile_picture;
            $data["caption"] = $value->caption->text;
            $data["postimage"] = $value->images->standard_resolution->url;

            array_push($response["data"], $data);
            $result = json_encode($response); 

    }

    return $result;
}

echo instagram();
?>

如果我这样做,它将适用于 JSON 的每个部分:

    $result .= '<li> 
                      '.$value->caption->from->username.'<br/>
                      '.$value->caption->from->profile_picture.'<br/>
                      '.$value->caption->text.'<br/>
                      '.$value->images->standard_resolution->url.'<br/>
                      '.$value->caption->created_time.'<br/>
                      </li>';

我觉得我在数组的某个地方遇到了麻烦,但我不完全确定。

【问题讨论】:

  • 您在 json 编码字符串周围添加了一些 html?我很困惑你想做什么
  • 忘记 HTML 的东西,我这样做只是为了在重新编码之前查看我从 Instagram 解析的数据。我只是说它会以这种方式从 Instagram 输出所有 16 个请求的帖子。

标签: php json instagram


【解决方案1】:

如果我们将 $response["data"] 和 $result 变量移出 foreach 会怎样?

你试过了吗?

$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {            

        $data = array();
        $data["createdtime"] = $value->caption->created_time;
        $data["username"] = $value->caption->from->username;
        $data["profileimage"] = $value->caption->from->profile_picture;
        $data["caption"] = $value->caption->text;
        $data["postimage"] = $value->images->standard_resolution->url;

        array_push($response["data"], $data);
}
$result = json_encode($response); 
return $result;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2019-12-05
    • 2014-10-10
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    相关资源
    最近更新 更多