php 如何将mysqli结果转换为JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3351882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert mysqli result to JSON?
提问by ab24
I have a mysqli query which I need to format as JSON for a mobile application.
我有一个 mysqli 查询,我需要将其格式化为移动应用程序的 JSON。
I have managed to produce an XML document for the query results, however I am looking for something more lightweight. (See below for my current XML code)
我已经设法为查询结果生成了一个 XML 文档,但是我正在寻找更轻量级的东西。(有关我当前的 XML 代码,请参见下文)
$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');
$stmt->execute();
$stmt->bind_result($title);
// create xml format
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);
// add node for each row
while($row = $stmt->fetch()) :
$occ = $doc->createElement('data');
$occ = $root->appendChild($occ);
$child = $doc->createElement('section');
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);
endwhile;
$xml_string = $doc->saveXML();
header('Content-Type: application/xml; charset=ISO-8859-1');
// output xml jQuery ready
echo $xml_string;
回答by Will
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
$row = $result->fetch_array(MYSQLI_ASSOC)$myArray[] = $row
$row = $result->fetch_array(MYSQLI_ASSOC)$myArray[] = $row
output like this:
输出如下:
[
{"id":"31","name":"pruduct_name1","price":"98"},
{"id":"30","name":"pruduct_name2","price":"23"}
]
If you want another style, you can try this:
如果你想要另一种风格,你可以试试这个:
$row = $result->fetch_row()$myArray[] = $row
$row = $result->fetch_row()$myArray[] = $row
output will like this:
输出将是这样的:
[
["31","pruduct_name1","98"],
["30","pruduct_name2","23"]
]
回答by Keith Brown
Here's how I made my JSON feed:
这是我制作 JSON 提要的方法:
$mysqli = new mysqli('localhost', 'user', 'password', 'myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
回答by DrColossos
As mentioned, json_encodewill help you. The easiest way is to fetch your results as you already do it and build up an array that can be passed to json_encode.
如上所述,json_encode会帮助你。最简单的方法是获取您已经完成的结果并构建一个可以传递给json_encode.
Example:
例子:
$json = array();
while($row = $stmt->fetch()){
$json[]['foo'] = "your content here";
$json[]['bar'] = "more database results";
}
echo json_encode($json);
Your $jsonwill be a regular array with each element in it's own index.
您$json将是一个常规数组,每个元素都在它自己的索引中。
There should be very little changed in your above code, alternativly, you can return both XML and JSON since most of the code is the same.
上面的代码应该几乎没有变化,或者,您可以同时返回 XML 和 JSON,因为大多数代码是相同的。
回答by Hamed Ahmad
I managed to run this code:
我设法运行此代码:
<?php
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
回答by Your Common Sense
There is one essential thing about JSON - the data mustbe UTF-8 encoded. Therefore, the proper encoding must be set for the database connection.
关于 JSON 有一件重要的事情——数据必须是 UTF-8 编码的。因此,必须为数据库连接设置正确的编码。
The rest is as silly as any other database operation
其余的和任何其他数据库操作一样愚蠢
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$mysql->set_charset('utf8mb4');
$sql = 'SELECT DISTINCT title FROM sections ORDER BY title ASC';
$data = $mysql->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($data);
回答by justnajm
If you have mysqlnd extension installed + enabled in php, you can use:
如果您在 php 中安装了 mysqlnd 扩展并启用,您可以使用:
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$result = $mysqli->query("SELECT * FROM phase1");
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
mysqli::fetch_all() needs mysqlnd driver to be installed before you can use it.
mysqli::fetch_all() 需要安装 mysqlnd 驱动程序才能使用它。

