如何使用PHP显示JSON数据
我已经创建了一个动态JSON文件 我的代码是:如何使用PHP显示JSON数据,php,json,Php,Json,我已经创建了一个动态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)); } 如何从JSO
$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循环或任何类似的方法?这是您在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'];
首先,在
循环中写入文件的方式是错误的。。因为您一次又一次地不必要地调用文件\u put\u 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\u get\u contents()
像这样
$jsonData = file_get_contents("product_file.json");
echo $jsonData; //<--- Prints your JSON
$jsonData=file_get_contents(“product_file.json”);
echo$jsonData// 在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" );
});
$.getJSON(“product_file.json”),函数(数据){
var项目=[];
$。每个(数据、函数(键、值){
items.push(“”+val+“ ”);
});
$(“
”{
“类”:“我的新列表”,
html:items.join(“”)
}).附于(“主体”);
});
首先,你在第2行有错误
而不是
mysql_fetch_array($respro)
其次,使用file_get_contents和json_decode函数
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
谢谢
mysql_fetch_array($respro)
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];