2014-04-26 94 views
-1

我已经创建了一个动态JSON文件。如何使用PHP显示JSON数据

我的代码是:

$res = mysql_query("select * from tbl_product where category='saree'"); 
while($rowpro=mysql_fetch_array($respro)) { 
    $records []= $rowpro; 
    $json_string=file_put_contents("product_file.json",json_encode($records)); 
} 

我怎样才能从JSON文件中的数据?使用while循环或类似的东西?

回答

0
$res = mysql_query("select * from tbl_product where category='saree'"); 
     while($rowpro=mysql_fetch_array($res)) 
      { 
       $records []= $rowpro; 
        $json_string=file_put_contents("product_file.json",json_encode($records)); 
      } 

首先,你有错误就行2

mysql_fetch_array($res) 

AND NOT

mysql_fetch_array($respro) 

其次,使用的file_get_contents和json_decode功能

$file=file_get_contents('php://input'); 
$obj = json_decode($file, true); 

$param = $obj['param']; 

感谢

0

这是你如何看到你的php文件中发布的json数据。

我宁愿:

$json_string=json_encode($records); 

您必须将头

header('Content-Type: application/json;charset=utf-8'); 

和对方

$file=file_get_contents('php://input'); 
$obj = json_decode($file, true); 

$param = $obj['param']; 
0

首先你在里面写入文件的方式while循环错误..因为你无意中调用file_put_contents()连连这简直是降低你的代码的性能..

因此重写代码到这个..

$res = mysql_query("select * from tbl_product where category='saree'"); 
while($rowpro=mysql_fetch_array($respro)) 
{ 
    $records[]= $rowpro;  
} 
file_put_contents("product_file.json",json_encode($records)); 

要读取JSON数据,利用file_get_contents()

喜欢这..

$jsonData = file_get_contents("product_file.json"); 
echo $jsonData; //<--- Prints your JSON 
0

在PHP中,

header('Content-Type: application/json;charset=utf-8'); 
$str = file_get_contents('product_file.json'); 
$jsonData = json_decode($str, true); //json decode 

而在jQuery中可以使用jQuery.getJSON例如,

$.getJSON("product_file.json", function(data) { 
var items = []; 
$.each(data, function(key, val) { 
    items.push("<li id='" + key + "'>" + val + "</li>"); 
}); 

$("<ul/>", { 
    "class": "my-new-list", 
    html: items.join("") 
    }).appendTo("body"); 
});