以json格式转换大数据

时间:2017-03-29 11:54:20

标签: php json

我有一个名为mobile的表,其中包含所有移动数据,其中有超过7000条记录,现在我想以json格式显示,但有些记录未显示在这里是我的代码请检查..

<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);

$myArray = array();


while($row = mysqli_fetch_assoc($result)){

    $myArray[] = $row;


}


mysqli_close($conn);

header('Content-Type: application/json');

//$json = file_get_contents('json.json');

/*

$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));

*/

$json = json_encode($myArray);

echo $json;


?>

enter image description here

3 个答案:

答案 0 :(得分:0)

我假设您可能正在使用ajax在您的php代码中使用var_dump()的浏览器中获取数据,然后是json标头,后跟json结果,这将无效。

为了设置标题,应该在打印出任何其他内容之前先调用header()函数,也不需要输入var转储。请尝试以下代码:

<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();

while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>

答案 1 :(得分:0)

您可以通过以下方式执行此操作:

var obj = JSON.parse($myArray);
echo obj;

答案 2 :(得分:0)

PHP中JSON_ENCODE的问题是,它往往会添加双引号和转义序列,这会增加导入的JSON的实际大小。所以,请试试这个。这对我有用。

<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);
$prefix = '';
echo '[';
foreach($myArray as $row) {
  echo $prefix, json_encode($row);
  $prefix = ',';
}
echo ']';
?>