用于Reddit的PHP和JSON

问题描述 投票:-2回答:1

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

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

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

(你可以用你试图查找的任何用户替换URL中的“tiagoperes”) - 谢谢汤姆查宾

问题:我收到错误消息

http错误500:reddiant.com/reddit.php

错误日志:

PHP警告:file_get_contents(https://www.reddit.com/user/tiagoperes/about.json):无法打开流:HTTP请求失败! HTTP / 1.1 403禁止在第5行

PHP致命错误:未捕获异常'InvalidArgumentException',消息'Passed变量不是数组或对象,而是使用空数组'在第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 json reddit
1个回答
2
投票

在第一个程序中遇到了一些麻烦,因此决定改变方法。

得到它的工作:

<?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'];
© www.soinside.com 2019 - 2024. All rights reserved.