2010-12-21 128 views
1

我從數據庫中檢索一個JSON數據即如何解析JSON到PHP

$result=array(); 
$query="SELECT * FROM fish"; 
$result1 = mysql_query($query, $conn); 
while ($table = mysql_fetch_array($result1, MYSQL_ASSOC)){ 
    $result[]=$table; 
} 
    echo json_encode($result);
,這給我的結果
[{"fish_id":"1","name":"first fish update","info":"this is my first fish update","image":"http:\/\/www.localhost\/cafe\/pics\/logout (1).gif"}]

但從另一個頁面,當我把這個JSON數據,即

$input = file_get_contents("http://localhost/fish/fish-json.php"); 
$json=json_decode($input); 
echo $json->fish_id;

它給我的錯誤

Notice: Trying to get property of non-object in /var/www/fish/json-to-php.php on line 13 Call Stack: 0.0005 318764 1. {main}() /var/www/fish/json-to-php.php:0
+0

當您回聲時,`$ input`是否包含任何結果? – Sarfraz 2010-12-21 13:06:40

+0

`print_r()`或`var_dump()`是你的朋友:)) – thedom 2010-12-21 13:12:07

回答

5

是對象的數組,所以

echo $json[0]->fish_id; 

要循環

if (!is_array($json)) die('...'); 
foreach ($json as $key=>$fish) 
{ 
    echo $fish->fish_id; 
} 
0

嘗試

$input = file_get_contents("http://localhost/fish/fish-json.php"); 
$json=json_decode($input); 
echo $json['fish_id']; 
0

嘗試echo $json['fish_id'];我可能會懷疑它,它轉換成數組

0

先試試這個:

echo $json; 

來檢查你是否有有效的json。 最終,fish-json.php中的php沒有執行。

0

默認情況下,json_decode返回一個stdClass對象。 您必須爲此功能提供第二個參數TRUE。

$json=json_decode($input, TRUE); 
echo $json[0]['fish_id'];