2017-01-19 25 views
-2

想要從特定的Reddit用戶抓取一些數據。PHP和JSON爲Reddit

在Reddit服務器上有一個可以遠程訪問的動態JSON文件。

的JSON文件路徑爲:http://www.reddit.com/user/tiagoperes/about.json

(在這裏您可以替換與任何用戶,您試圖查找該URL「tiagoperes」) - 謝謝湯姆蔡平

問題 :我收到錯誤消息

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

解決方案:詢問調試。

這是什麼問題?

無法找到使其工作的方法,應該很簡單。

謝謝!

+1

究竟是什麼'**問題:**頁面甚至不load.'意味着 – RiggsFolly

+0

好了,所以'的file_get_contents()'是不是**第7行**您正在向我們展示的代碼。 **向我們顯示真實的代碼,如果你想要一個真實的答案** – RiggsFolly

+0

再次檢查,有: <?php phpinfo(); ?> 頂部 – brotherperes

回答

1

在第一個程序中遇到了一些麻煩,所以決定改變方法。

得到它這樣的工作:

<?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'];