2014-04-26 93 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"); 
});