如何將mysqli查詢結果轉換為JSON格式?
P粉794851975
P粉794851975 2023-08-22 14:56:27
0
2
512
<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) 或 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粉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"]
]
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板