如何将mysqli结果转换为JSON?

2022-08-30 12:47:24

我有一个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;

答案 1

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

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

答案 2

以下是我如何制作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();

推荐