gpt4 book ai didi

php - 如何将 mysqli 结果转换为 JSON?

转载 作者:IT老高 更新时间:2023-10-28 12:51:37 26 4
gpt4 key购买 nike

我有一个 mysqli 查询,我需要为移动应用程序格式化为 JSON。

我已经成功地为查询结果生成了一个 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;

最佳答案

只需根据查询结果创建一个数组,然后对其进行编码

$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
$result = $mysqli->query("SELECT * FROM phase1");
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);

输出如下:

[
{"id":"31","name":"product_name1","price":"98"},
{"id":"30","name":"product_name2","price":"23"}
]

如果你想要其他样式,可以将 fetch_assoc() 更改为 fetch_row() 并获得如下输出:

[
["31","product_name1","98"],
["30","product_name2","23"]
]

关于php - 如何将 mysqli 结果转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3351882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com