用PHP

2016-08-01 38 views
0

訪問JSON我想讀的頁面http://mattrb.com/txt.txt用PHP

例如在JSON數據,讓我們說我想要得到的名稱爲「妙蛙種子。」我有這樣的代碼:

<?php 
    $file = file_get_contents("http://mattrb.com/txt.txt"); 
    $json = json_decode($file); 
    echo $json->1->name; 
?> 

此代碼會導致php無法加載。這是因爲你不能使用數字嗎?接下來我嘗試了這個:

<?php 
    $file = file_get_contents("http://mattrb.com/txt.txt"); 
    $json = json_decode($file); 
    $num = 1; 
    echo $json->$num->name; 
?> 

這允許php加載,但仍然沒有返回任何內容。我究竟做錯了什麼?

+0

是$ json這是一個對象嗎?使用var_dump來知道你從這個文件得到的是什麼 –

+0

嘗試'print json_last_error();'之前。 – mario

回答

0

你的json不應該包含換行符和其他無效字符。 換句話說 - 你的json無效。 json_decode在文件上不起作用。

$file = file_get_contents("http://mattrb.com/txt.txt"); 
var_dump(json_decode($file)); 
// NULL 
0

您的json無效。請檢查http://jsonlint.com/。你也可以像這樣訪問php中的「1」:echo $ json - > {1} - > name;

0

你的json文件不是valide你有一個逗號問題項目編號135嘗試刪除它,所以你可以解析文件。

"135": {, //the problem of your json data is here 
    "levels": [5, 15], 
    "probability": 4 "name": "Jolteon", 
    "attack": 65, 
    "defense": 60, 
    "type": "electric", 
    "moves": [ 
     "tackle", 
     "thundershock", 
     "thunder" 
    ], 
    "curve": 1.6 
}, 
+0

提供的json中有更多的錯誤。嘗試http://jsonlint.com/ – omxv