如何使用PHP显示JSON数据

时间:2014-04-26 07:30:09

标签: 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));
}

如何从JSON文件中获取数据?使用while循环或类似的东西?

4 个答案:

答案 0 :(得分: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'];

答案 1 :(得分:0)

首先,您在while循环内写入文件的方式是错误的。因为您不必要地一次又一次地调用file_put_contents(),这只会降低您的代码性能.. < / p>

所以重写你的代码..

$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

答案 2 :(得分: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" );
 });

答案 3 :(得分: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'];

谢谢

相关问题