如何从TXT文件中提取Open Graph信息?

时间:2012-04-13 21:31:50

标签: php json parsing text-files

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

{
    "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);
?>

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

请帮帮忙?

1 个答案:

答案 0 :(得分: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;
            ?>