如何将mysqli查询结果转换为JSON格式?
P粉794851975
P粉794851975 2023-08-22 14:56:27
0
2
393

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

我已经成功生成了一个查询结果的XML文档,但我正在寻找更轻量级的解决方案。(请参见下面的当前XML代码)

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('连接数据库时出现问题'); $stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC'); $stmt->execute(); $stmt->bind_result($title); // 创建xml格式 $doc = new DomDocument('1.0'); // 创建根节点 $root = $doc->createElement('xml'); $root = $doc->appendChild($root); // 为每一行添加节点 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'); // 输出xml,jQuery准备就绪 echo $xml_string;


P粉794851975
P粉794851975

全部回复 (2)
P粉151466081

这是我创建JSON feed的方法:

$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();
    P粉044526217

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

    $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"] ]
      最新下载
      更多>
      网站特效
      网站源码
      网站素材
      前端模板
      关于我们 免责声明 Sitemap
      PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!