0

我有一个 TXT 文件,其中包含一些 facebook Open Graph 信息,如下所示:

{
    "data": [
      {
        "name": "Avatar", 
        "category": "Movie", 
        "id": "82771544063", 
        "created_time": "2012-04-13T21:16:56+0000"
      }, 
      {
        "name": "HappyDance", 
        "category": "Movie", 
        "id": "243564344063", 
        "created_time": "2012-04-13T21:16:56+0000"
      } 
    ], 
    "paging": {
        "next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
    }
}

在 PHP 中,我想从显示的行中提取所有 id 号

"id": "XXXXXXXXXXXX", 

输出应如下所示:

I like 8277564344063
I like 243564344063

我开始了以下操作,但出现错误:

<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();

$text = file_get_contents('raw.txt');
$decode = json_decode($text);

print_r($decode);

$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);

fclose($file_handle);
?>

错误是我的输出是空白的!我究竟做错了什么?

请帮忙?

4

1 回答 1

2

您没有有效的 JSON。

此行下方的 JSON对象是有效的 JSON。我在“数据”数组中的最后一个关联数组之后删除了逗号。数组末尾不需要逗号。

        {
            "data": [
              {
                "name": "Avatar", 
                "category": "Movie", 
                "id": "82771544063", 
                "created_time": "2012-04-13T21:16:56+0000"
              }, 
              {
                "name": "HappyDance", 
                "category": "Movie", 
                "id": "243564344063", 
                "created_time": "2012-04-13T21:16:56+0000"
              }
            ], 
            "paging": {
                "next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
            }
        }


Parse error on line 14:
...    },            ],    "paging": { 
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

当我从无效的 JSON 中删除逗号时。我能够得到你想要的结果。

            <?php
                $json_object = file_get_contents('fb.json');
                if(!$json_object) {
                                      echo "oops, cant read the file";
                                    }

                 // remap json_object
                 $json_object = json_decode($json_object,true);

                    foreach($json_object['data'] as $item) {
                            $items[] = "I like" . ' ' . $item['id'];

                      /* If you want to just echo " I like xyz" etc
                       * use echo "I like" . $item['id'];
                       */
                        }

                  $list = implode(',',$items);

                  echo $list;
            ?> 
于 2012-04-13T23:51:05.260 回答