首页  >  问答  >  正文

如何将mysqli查询结果转换为JSON格式?

<p>我有一个mysqli查询,我需要将其格式化为适用于移动应用程序的JSON。</p> <p>我已经成功生成了一个查询结果的XML文档,但我正在寻找更轻量级的解决方案。(请参见下面的当前XML代码)</p> <pre class="brush:php;toolbar:false;">$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;</pre> <p><br /></p>
P粉794851975P粉794851975446 天前485

全部回复(2)我来回复

  • P粉151466081

    P粉1514660812023-08-23 12:44:56

    这是我创建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();

    回复
    0
  • P粉044526217

    P粉0445262172023-08-23 09:42:01

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

    $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"]
    ]

    回复
    0
  • 取消回复