2010-12-21 80 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'];