PHP 和 JSON 用于 Reddit

PHP and JSON for Reddit

想从特定的 Reddit 用户那里获取一些数据。

Reddit 服务器上有一个可以远程访问的动态 JSON 文件。

JSON文件路径为:http://www.reddit.com/user/tiagoperes/about.json

(您可以将 URL 中的“tiagoperes”替换为您要查找的任何用户)- 谢谢 Tom Chapin

问题:我收到错误消息

http error 500: reddiant.com/reddit.php

错误日志:

PHP Warning: file_get_contents(https://www.reddit.com/user/tiagoperes/about.json): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden on line 5

PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Passed variable is not an array or object, using empty array instead' on line 8

代码:

<?php


$url = "https://www.reddit.com/user/tiagoperes/about.json";
$json = file_get_contents($url);

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}

(灵感来源于此:http://codepad.org/Gtk8DqJE

解决方法:求调试

这里有什么问题?

找不到让它工作的方法,应该很简单。

谢谢!

在第一个过程中遇到了一些麻烦,所以决定改变方法。

让它像那样工作:

<?php
    $opts = array(
    'http'=>array(
    'method'=>"GET",
    'header'=>"User-Agent: reddiant api script\r\n"
    ));

    $context = stream_context_create($opts);
    $url = "http://www.reddit.com/user/tiagoperes/about.json";
    $json = file_get_contents($url, false, $context);

    $result = json_decode($json, true);

    // Result:
    var_dump($result);

    //echo data
    echo $result['data']['name'];